考虑出界位置为 6 和 -6。
我想让船掉头朝相反的方向移动。
这是我的代码..它仍然没有100%按照我想要的方式工作。我很好奇看看有没有人 有任何想法如何改进。 这是我的代码的逻辑。
//If the ship hits a boundary it turns around and moves in the opp.
//direction. To do this, the ship's velocty should be flipped from a
//negative into a positive number, or from pos to neg if boundary
//is hit.
//if ship position is -5 at velocity -1 new ship pos is -6
//if ship position is -6 at velocity -1 new ship velocity is +1
// new ship position is +5
这是我的代码:
public void move()
{
position = velocity + position;
if (position > 5)
{
velocity = -velocity;
}
else if (position < -5)
{
velocity = +velocity;
}
}
最佳答案
代码velocity = +velocity;
不会将负速度更改为正速度。这相当于将速度乘以 +1
,但不会改变符号。
要在出界时翻转速度符号,您需要始终乘以-1
。
不太清楚界限是什么,所以下面我假设它们是 6 和 -6。
position += velocity;
//make sure the ship cannot go further than the bounds
//but also make sure that the ship doesn't stand still with large velocities
if (position > 6)
{
velocity = -velocity;
position = 6;
}
if (position < -6)
{
velocity = -velocity;
position = -6;
}
关于java - 如何使物体转向相反的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18871247/