Calculate the movement of a point with an angle in java

我是研究僧i 提交于 2019-12-11 01:38:48

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/33127413/calculate-the-movement-of-a-point-with-an-angle-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!