简体   繁体   中英

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM