无法实现对鼠标JAVA的对象旋转

时间:2016-12-31 11:38:24

标签: java swing rotation mouselistener

正如标题所说,不能做到。试图很长时间但仍然失败。 (我是java的新手)
我的图像或fillRect稍微旋转但不应旋转
整码+ imgs


    *MAIN game class*
    package game.main;

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.image.BufferStrategy;

    public class game extends Canvas implements Runnable{

        private static final long serialVersionUID = -392333887196083915L;

        public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;
        private Thread thread;
        private boolean running = false;

        private Handler handler;

        public game(){

            handler = new Handler();

            new window(WIDTH, HEIGHT,"Game",this);

            handler.addObject(new Player(WIDTH/2-32, HEIGHT/2-32, ID.Player, handler));
        }

        public synchronized void start(){
            thread = new Thread(this);
            thread.start();
            running = true;
        }
        public synchronized void stop(){
            try{
                thread.join();
                running = false;
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        // ↓ game loop for update
        public void run(){
            this.requestFocus();
            long lastTime = System.nanoTime();
            double amountOfTicks = 60.0;
            double ns = 1000000000 / amountOfTicks;
            double delta = 0;
            long timer = System.currentTimeMillis();
            int frames = 0;
            while(running){
                long now = System.nanoTime();
                delta += (now - lastTime) / ns;
                lastTime = now;
                while(delta >= 1){
                    tick();
                    delta--;
                }
                if(running)
                    render();
                frames++;

                if(System.currentTimeMillis() - timer > 1000){
                    timer += 1000;
                    System.out.print("FPS:" + frames);
                    frames = 0;
                }
            }
            stop();
        }

        private void tick(){
                    handler.tick();             
                }

        private void render(){
            BufferStrategy bs = this.getBufferStrategy();
            if(bs == null){
                this.createBufferStrategy(3);
                return;
            }

            Graphics g = bs.getDrawGraphics();

            g.setColor(Color.black);
            g.fillRect(0, 0, WIDTH, HEIGHT);

            handler.render(g);

            g.dispose();
            bs.show();
        }



        public static void main(String args[]) {
            new game();
        }


    }
<br>
package game.main;

import java.awt.Graphics;

public abstract class GameObject {

    protected float x, y;
    protected ID id;
    protected float velX, velY;

    public GameObject(float x, float y, ID id){
            this.x = x;
            this.y = y;
            this.id = id;
    }

    public abstract void tick();
    public abstract void render(Graphics g);

    public void setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }   
    public float getX(){
        return x;
    }
    public float getY(){
        return y;
    }
    public void setId(ID id){
        this.id = id;
    }
    public ID getId(){
        return id;
    }
    public void setVelX(int velX){
        this.velX = velX;
    }
    public void setVelY(int velY){
        this.velY = velY;
    }
    public float getVelX(){
        return velX;
    }
    public float getVelY(){
        return velY;
    }
}


*GameObject class*
package game.main;

import java.awt.Graphics;

public abstract class GameObject {

    protected float x, y;
    protected ID id;
    protected float velX, velY;

    public GameObject(float x, float y, ID id){
            this.x = x;
            this.y = y;
            this.id = id;
    }

    public abstract void tick();
    public abstract void render(Graphics g);

    public void setX(int x){
        this.x = x;
    }
    public void setY(int y){
        this.y = y;
    }   
    public float getX(){
        return x;
    }
    public float getY(){
        return y;
    }
    public void setId(ID id){
        this.id = id;
    }
    public ID getId(){
        return id;
    }
    public void setVelX(int velX){
        this.velX = velX;
    }
    public void setVelY(int velY){
        this.velY = velY;
    }
    public float getVelX(){
        return velX;
    }
    public float getVelY(){
        return velY;
    }
}


*Handler class*
package game.main;

import java.awt.Graphics;
import java.util.LinkedList;

// render all objects
public class Handler {

    LinkedList<GameObject> object = new LinkedList<GameObject>();

    public void tick(){
        for(int i = 0; i < object.size(); i++){
            GameObject tempObject = object.get(i);

            tempObject.tick();      
        }
    }
    public void render(Graphics g){
        for(int i = 0; i <object.size();i++){
            GameObject tempObject = object.get(i);

            tempObject.render(g);
        }
    }// handling adding objects
    public void addObject(GameObject object){
        this.object.add(object);
    }   
}


*window class*
package game.main;

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class window extends Canvas{

    private static final long serialVersionUID = 3010486623466540351L;

    public window(int width, int height, String title, game game){
        JFrame frame = new JFrame(title);

        frame.setPreferredSize(new Dimension(width, height));
        frame.setMaximumSize(new Dimension(width, height));
        frame.setMinimumSize(new Dimension(width, height));

        // X button
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // ¤ button maximize
        frame.setResizable(false);
        // window appear in middle of screen instead of top left corner
        frame.setLocationRelativeTo(null);
        // add game to window
        frame.add(game);
        frame.setVisible(true);
        game.start();
    }       
}


* ID class*
package game.main;

public enum ID {

    Player();
}


仅对此类添加代码

*Player class*
package game.main;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;

public class Player extends GameObject{

    Handler handler;

    public Player(int x, int y, ID id, Handler handler) {
        super(x, y, id);
        this.handler = handler;
    }

    public void tick() {
    }
    public void render(Graphics g) {
        ///////////ADDED//////////////////
        PointerInfo a = MouseInfo.getPointerInfo();
        Point b = a.getLocation();
        int mouseX = (int) b.getX();
        int mouseY = (int) b.getY();
        int centerX = game.WIDTH / 2;
        int centerY = game.HEIGHT / 2;
        double angle = Math.atan2(centerY - mouseY, centerX - mouseX) - Math.PI / 2;
        ((Graphics2D)g).rotate(angle, centerX, centerY);
        //////////////////////////////
        g.setColor(Color.white);
        g.fillRect((int)x, (int)y, 32, 32);

    }
}


它现在如何工作以及我想要它。白色 - 原始/绿色 - 我希望它像那样 Example 1
Example 2
我查看了这些消息来源:
Get mouse possition (stackoverflow)
Java 2d rotation in direction mouse point (stackoverflow)
Rotating an object to point towards the mouse

1 个答案:

答案 0 :(得分:0)

问题是MouseInfo.getPointerInfo().getLocation();返回绝对鼠标位置。您需要相对于游戏画布的鼠标位置。您可以按如下方式修改render课程中的game方法:

 Point mouseLocation = MouseInfo.getPointerInfo().getLocation();
 SwingUtilities.convertPointFromScreen(mouseLocation, this);
 handler.render(g, mouseLocation);

这要求您相应地修改渲染方法的方法签名。这只是将mouseLocation从游戏画布传递到Player的渲染方法的一种方法。 在播放器的渲染方法中使用mouseLocation代替MouseInfo.getPointerInfo().getLocation();

还有一些事情你需要改变才能将玩家置于画布的中心并让他围绕他的中心旋转:

  • 您应该设置游戏画布的大小而不是窗口的大小(JFrame)。通过在游戏画布上调用setPreferredSize(new Dimension(width, height));并在frame.pack()之前调用frame.setVisible(true)来执行此操作。这将确保您的游戏画布具有WIDTHHEIGHT指定的大小。
  • 您可以在refx课程中添加两个字段refyGameObject,其中描述了GameObject的参考点(例如其中心)。然后,您可以通过调用Player来构建新的new Player(WIDTH/2-16, HEIGHT/2-16, 16, 16, ID.Player, handler),其中玩家的初始位置位于(WIDTH / 2-16,HEIGHT / 2-16)它的参考点是(16,16) - 当玩家用32x32矩形表示时玩家的中心。
  • 在玩家的渲染方法中初始化你要用int centerX = Math.round(x + refx); int centerY = Math.round(y + refy);旋转的中心,其中(x,y)是你要旋转的对象的位置,(refx,refy)点你想相对于物体的位置旋转(例如x = WIDTH / 2-16,y = HEIGTH / 2-16,refx = 16,refy = 16)。< / LI>