如何在出界时让船停止移动?

时间:2013-09-18 05:09:49

标签: java

我遇到了这段代码的问题,如果有人能指出我正确的方向,我将非常感激。已经坚持了几天!!

基本上我试图阻止船一旦到达边界就移动。 边界是6和-6。

这是代码。谢谢:))

public void move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5)
    {
        .... ?? What to write here?

    }
    else if (position < -5)
    {
        .... ?? What to write here?

    }

    position = position + direction;
    gun1.move(direction);
    gun2.move(direction);

}

3 个答案:

答案 0 :(得分:2)

问题取决于。如果你想在物体到达边界时停止它,那么就像......

// Move first
position = position + direction;

// Boundary check second...
if (position > 5)
{
     position = 5;
}
else if (position < -5)
{
     position = -5;
}

gun1.move(direction);
gun2.move(direction);

如果你想“反弹”墙壁......

// Move first
position = position + direction;

// Boundary check second...
if (position > 5)
{
     position = 5;
     direction *= -1
}
else if (position < -5)
{
     position = -5;
     direction *= -1
}

gun1.move(direction);
gun2.move(direction);

可能会工作 - 没有更多的背景很难说出来......

答案 1 :(得分:2)

即使他试图离开边界,这也会让玩家保持在边界

public void move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5)
    {
        position = 5;

    }
    else if (position < -5)
    {
        position = -5;

    }

    position = position + direction;
    gun1.move(direction);
    gun2.move(direction);

}

答案 2 :(得分:0)

您的方法必须将状态(已移动或未移动)传达给调用代码。 您可以通过以下两种方式完成此任务:

1返回状态代码

public int move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5 || position <-5)
    {
        return -1;   //status code for no movement

    }

2当船不能移动时抛出异常

public void move (int direction) throws InvalidArgumentException//if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5 || position <-5)
    {
        throw new InvalidArgumentException("Cannot move!");   //status code for no movement

    }

调用代码可以处理状态代码/异常,看它是否合适。

相关问题