2015-10-14 28 views
2

对于我们正在制作顶视图游戏的项目。角色可以转向并在各个方向行走,并以点和角度表示。角度计算为当前方向和程序顶部之间的角度,可以是0-359。用java计算一个角度点的移动

我对运动以下代码:

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

移动时上下,并且可以打开,但只要你把这个工作好,左,右功能似乎是想在错误的方向(不只是90度的角度),有时开关

回答

5

这个怎么样:对所有的移动方法使用相同的算术,只是改变你移动的角度。

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