我正在使用简单的方法在游戏中移动一个单位,例如:获取该位置以北的位置。但我想要不同的单位具有不同的速度,我对如何做到这一点有点困惑。 职位类别:
public class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public Position getPosToNorth() {
Position position = new Position(getX(), getY() - 1);
return position;
}
}
然后在我的其他类(class)中我得到了这个移动方法:
public void move()
{
if(this.direction == "North")
{
setPosition(getPosition().getPosToNorth());
}
}
如果我有一个变量,假设:speed = 10;我如何使用它来影响我的单位移动的距离?我能否以某种方式将速度变量从其他类获取到我的 Position 类中,而不是采用 getY() - 1 而是采用 getY() - speed ?我尝试过,但没有成功...提前致谢。
最佳答案
答案取决于你的世界是如何定义的:
- 是否有像图 block 这样的离散位置?我认为是的,因为您使用的是整数坐标。
- 单位允许对角移动吗?如果是的话,事情就会变得有点复杂。
基本上,您只需根据当前坐标计算新位置并相应地添加/减去速度(但是在您的情况下定义)。
我会做这样的事情:
enum Direction {
NORTH( 0, -1),
SOUTH( 0, 1 ),
EAST( 1, 0).
WEST( -1, 0);
int x;
int y;
//constructor and getters
}
Position move(Direction dir, int speed) {
return new Position(x + dir.getX() * speed, y + dir.getY() * speed);
}
关于java - 使用变量影响我的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27290742/