0

考虑出界位置是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;
    }
}
4

5 回答 5

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;
}
于 2013-09-18T11:51:41.730 回答
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;
}
于 2013-09-18T11:52:02.623 回答
0

当它到达边界时,将速度乘以 -1。

于 2013-09-18T11:47:44.290 回答
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;
}
于 2013-09-18T11:48:53.080 回答
0

如果你想让它改变方向,你需要翻转标志。这是相同的* -1或否定它。

public void move() {    
    // prevent it jumping through the wall.
    if (Math.abs(position + velocity) > 5)
        velocity = -velocity;

    position += velocity;
}
于 2013-09-18T11:52:20.590 回答