用Java计算带有角度的点的移动 [英] Calculate the movement of a point with an angle in java

查看:173
本文介绍了用Java计算带有角度的点的移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个项目,我们正在制作一个自上而下的游戏.角色可以向各个方向旋转和行走,并以一个点和一个角度来表示.该角度被计算为当前朝向和程序顶部之间的角度,可以为0-359.

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.

我有以下运动代码:

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度角),有时会切换

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

这篇关于用Java计算带有角度的点的移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆