考虑到超出界限的位置是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;
}
}
答案 0 :(得分:1)
你可以这样做:
public void move()
{
//first check where the next move will be:
if ((position + velocity) > 5 || (position + velocity) < -5){
// Here we change direction (the velocity is multiplied for -1)
velocity *= -1;
}
position += velocity;
}
答案 1 :(得分:1)
代码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;
}
答案 2 :(得分:0)
当它到达边界时,将速度乘以-1。
答案 3 :(得分:0)
首先,你的逻辑看起来有点瑕疵。如果位置 -6 且速度 -1 ,要开始向相反方向移动,您的新位置应 -5 (而不是 +5 )和速度 +1 。
此外,只要您的位置达到边界条件,您就需要反转速度符号。
public void move() {
if (Math.abs(position + velocity) > 5) { // Check for boundary conditions
velocity *= -1;
}
position = position + velocity; // position += velocity;
}
答案 4 :(得分:0)
如果你想改变方向,你需要翻转标志。这与* -1
相同或否定它。
public void move() {
// prevent it jumping through the wall.
if (Math.abs(position + velocity) > 5)
velocity = -velocity;
position += velocity;
}