向光标移动“项目符号”(略微关闭)

时间:2018-11-25 16:13:56

标签: java

它可以工作,但是项目符号始终会略微位于光标上方,而不是直接穿过光标。我花了最后2个小时试图弄清楚,去了google,我想我只是在挖个洞。

抱歉,代码混乱,当我陷入困境时,我只是忘了整理一下代码,因为我一直专注于使其工作正常……

public class RenderSpace extends JPanel implements ActionListener, KeyListener{

    int boardHeight = 600;
    int boardWidth = 800;


    private Boolean fire = false;

    Point mouse =  new Point(0,0);

    int mouseX = 0;
    int mouseY = 0;

    Timer play;

    RenderSpace(){
        setPreferredSize(new Dimension(boardWidth,boardHeight));
        setBackground(Color.black);
        setVisible(true);
        setFocusable(true);
        startAction();
        addKeyListener(this);
    }

    public void startAction() {
        play = new Timer(100,this);
        play.start();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        draw(g);
    }       


    int bulletX = 395;
    int bulletY = 567;

    public void draw(Graphics g) {
        int deltax = 400 - mouse.x;
        int deltay = 567 - mouse.y;         

        Graphics2D g2d = (Graphics2D) g.create();           

        //rotates cannon to point towards mouse
        g2d.rotate(-Math.atan2(deltax,deltay),400,567);
        g2d.setColor(Color.white);
        g2d.fillRect(395, 530, 10, 25);

        //creates a base for the cannon
        g.setColor(Color.white);
        g.fillRect(388,550, 25, 25);


        //create the bullet and repaints it to move towards cursor
        g.setColor(Color.red);
        g.fillOval(bulletX,bulletY, 10, 10);

    }

    public void bullet() {
        double bulletVelocity = 10.0;

        int deltax = mouseX - 400;
        int deltay = mouseY - 567;   

        double angle = Math.atan2(deltax,deltay);
        double yVelocity = (bulletVelocity) * Math.sin(angle);
        double xVelocity = (bulletVelocity) * Math.cos(angle);

        bulletY += xVelocity;
        bulletX += yVelocity;  
    }

    public void actionPerformed(ActionEvent arg0) {
        mouse = getMousePosition();

        if(fire == true) {
            bullet();
        }
        repaint();
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE) {
            fire = true;
            mouseX = mouse.x ;
            mouseY = mouse.y;
        }
    }
}

我认为问题是何时将速度转换为整数?就像我说的那样,它的工作原理是不直接通过mouseX和mouseY。

0 个答案:

没有答案