I am making a game similar to Asteroids. The ship always points toward the mouse cursor. I want to know how to move towards the mouse so if I press w I will drive towards the mouse and if I press s I will move away from the mouse. How can I do this? Here is my code so far:

public class player {

    public int x,y;
    private Image img;

    float xDistance;
    float yDistance;
    double rotationAngle;

    public player(int x,int y){
        this.x = x;
        this.y = y;

    public void tick(){
         xDistance = Comp.mx - x;
         yDistance = Comp.my - y;
         rotationAngle = Math.toDegrees(Math.atan2(yDistance, xDistance));

    public void render(Graphics g){
        Graphics2D g2 = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);

        ImageIcon i2 = new ImageIcon("res/player.png");
        img = i2.getImage();

        AffineTransform at = AffineTransform.getTranslateInstance(x, y);
        at.rotate(Math.toRadians(rotationAngle) ,20,20);

        g2.drawImage(img, at, null);


    public void handleinput(){



1 Answer 1


There are a few steps that you need to follow to accomplish this goal, they are as follows:

  • Get the distance that the player has moved (i.e. the amount of time the w key has been pressed times some sort of speed multiplier)
  • Calculate the distance along the x- & y-axis that the ship should be displaced using the trigonometric functions sine and cosine
  • Move the ship relative to these amounts

The diagram below shows how the vertical and horizontal displacements relate to the distance the player moved in the asteroids game.

player movement mechanics

Suppose that your cursor makes an angle that is 30 degrees, or π/6 radians, relative to the x-axis and the ship moves a total of 15 pixels toward its target. The horizontal displacement of the ship is then 15×cos(π/6)=12.99≈13 pixels and the vertical displacement is 15×sin(π/6)=7.5≈8 pixels.

Hope that helps, and sorry for the lack of code. I'm not that familiar with the native Java libraries for drawing graphics.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .