Search code examples
javamathpointangle

Calculate the movement of a point with an angle in java


For a project we're making a topdown-view game. Characters can turn and walk in all directions, and are represented with a point and an angle. The angle is calculated as the angle between the current facing direction and to the top of the program, and can be 0-359.

I have the following code for the movement:

public void moveForward()
{
    position.x = position.x + (int) (Math.sin(Math.toRadians(angle)) * speed);
    position.y = position.y + (int) (Math.cos(Math.toRadians(angle)) * speed);
}

public void strafeLeft()
{
    position.x = position.x - (int) (Math.cos(Math.toRadians(angle)) * speed);
    position.y = position.y - (int) (Math.sin(Math.toRadians(angle)) * speed);
}

public void strafeRight()
{
    position.x = position.x + (int) (Math.cos(Math.toRadians(angle)) * speed);
    position.y = position.y + (int) (Math.sin(Math.toRadians(angle)) * speed);
}

public void moveBackwards()
{

    position.x = position.x - (int) (Math.sin(Math.toRadians(angle)) * speed);
    position.y = position.y - (int) (Math.cos(Math.toRadians(angle)) * speed);
}

public void turnLeft()
{
    angle = (angle - 1) % 360;
}

public void turnRight()
{
    angle = (angle + 1) % 360;
}

This works good when moving up and down, and can turn, but as soon as you turn, the left and right functions seem to be going in wrong directions (not just 90 degree angles), and sometimes switch


Solution

  • How about this: use the same arithmetic for all of your move methods, and just vary what angle you move along.

    public void move(int some_angle){
        position.x = position.x + (int) (Math.sin(Math.toRadians(some_angle)) * speed);
        position.y = position.y + (int) (Math.cos(Math.toRadians(some_angle)) * speed);
    }
    
    public void moveForward()
    {
        move(angle);
    }
    
    public void strafeLeft()
    {
        move(angle+90);
    }
    
    public void strafeRight()
    {
        move(angle-90);
    }
    
    public void moveBackwards()
    {
        move(angle+180);
    }