考虑到出界位置是6和-6。
我想让这艘船掉头朝相反的方向移动。
这是我的密码..。它仍然不能百分之百地发挥我想要的效果。我很好奇,想看看有没有人想过如何改进。这是我的代码的逻辑。
//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;
}
}
发布于 2013-09-18 03:52:02
代码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;
}
发布于 2013-09-18 03:51:41
你可以这样做:
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;
}
发布于 2013-09-18 03:47:44
当它到达一个边界时,将速度乘以-1。
https://stackoverflow.com/questions/18871247
复制相似问题