Java 如何使一个物体旋转并向相反方向移动?

Java 如何使一个物体旋转并向相反方向移动?,java,Java,考虑到越界位置为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 positiv

考虑到越界位置为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;
    }
}
公共作废移动()
{
位置=速度+位置;
如果(位置>5)
{
速度=-速度;
}
否则,如果(位置<-5)
{
速度=+速度;
}
}

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

首先,您的逻辑看起来有点缺陷。如果位置为-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;
}
您可以这样做:

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;
}
公共作废移动()
{
//首先检查下一步将在哪里:
如果((位置+速度)>5 | |(位置+速度)<-5){
//这里我们改变方向(速度乘以-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;
}
位置+=速度;
//确保船不能超过边界
//但也要确保船不会以很大的速度静止不动
如果(位置>6)
{
速度=-速度;
位置=6;
}
如果(位置<-6)
{
速度=-速度;
位置=-6;
}

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

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

    position += velocity;
}

你的逻辑看起来有点错误。如果位置为-6,速度为-1,要开始向相反方向移动,新位置应为-5(而不是+5),速度为+1。这不起任何作用
velocity=+velocity也许你的意思是
velocity=-velocity这将不起作用,因为在速度改变之前,实际位置将为6。。这是不可能的bound@Gianmarco你能再检查一下我有什么吗。我改变了它,这样在位置改变之前速度就改变了。为什么不为-1乘法呢?@Gianmarco乘法比否定要昂贵。对于这个用例,这并不重要。真的更贵吗?6是越界的,我认为它不应该达到越界位置,而是应该在…@Gianmarco之前改变速度-在这种情况下,我们只需要在更新位置之前放置
if
!是的,正如我在回答中所做的:)我认为它永远不会达到第6位或-6位。。。因为他们出界了。@Gianmarco哦,好的。在这种情况下,只需在if条件之后进行更新,并更改if边界。我会编辑。正如我在回答中所做的那样,我认为在你翻转速度后,这仍然会跳出边界。例如,考虑6的速度和0的位置。我们不知道速度是否应该是任何值,我认为速度等于方向。也许我错了,那样的话你的答案就行了+1.