如何让图像随机移动?

时间:2011-10-03 09:38:40

标签: java jpanel runnable

我在面板内有一个图像,它以顺时针方向移动。现在,我希望它随机移动,这是我的问题。

有人可以告诉我该怎么做吗?

这是我尝试过的:

private int xVelocity = 1;
private int yVelocity = 1;
private int x, y;
private static final int RIGHT_WALL = 400;
private static final int UP_WALL = 1;
private static final int DOWN_WALL = 400;
private static final int LEFT_WALL = 1;

public void cycle()
{       

    x += xVelocity;
    if (x >= RIGHT_WALL)
    {
        x = RIGHT_WALL;
        if (y >= UP_WALL)
        {
            y += yVelocity;
        }

    }

   if (y > DOWN_WALL)
    {
        y = DOWN_WALL;
        if (x >= LEFT_WALL)
       {
            xVelocity *= -1;
        }
    }


    if (x <= LEFT_WALL)
    {

        x = LEFT_WALL;
        if (y <= DOWN_WALL)
        {
            y -= yVelocity;
        }

    }

    if (y < UP_WALL)
    {
        y = UP_WALL;
        if (x <= RIGHT_WALL)
        {
            xVelocity *= -1;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

更改

y -= yVelocity;

if (y>0) {
    y = -1*Random.nextInt(3);
} else {
    y = Random.nextInt(3);
}

答案 1 :(得分:2)

调用这样的方法来设置随机方向:

public void setRandomDirection() {
  double direction = Math.random()*2.0*Math.PI;
  double speed = 10.0;
  xVelocity = (int) (speed*Math.cos(direction));
  yVelocity = (int) (speed*Math.sin(direction));
}

注意到你的循环方法需要一点点修复才能发挥作用。

public void cycle() {
  x += xVelocity;
  y += yVelocity; //added
  if (x >= RIGHT_WALL) {
    x = RIGHT_WALL;
    setRandomDirection();//bounce off in a random direction
  }
  if (x <= LEFT_WALL) {
    x = LEFT_WALL;
    setRandomDirection();
  }
  if (y >= DOWN_WALL) {
    y = DOWN_WALL;
    setRandomDirection();
  }
  if (y <= UP_WALL) {
    y = UP_WALL;
    setRandomDirection();
  }
}

(它有效,但这不是最有效/优雅的方式)

如果你想要某种“随机游走”,试试这样的事情:

public void cycle() {
  //move forward
  x += xVelocity;
  y += yVelocity;

  if (Math.random() < 0.1) {//sometimes..
    setRandomDirection();   //..change course to a random direction
  }
}

你可以增加0.1(最大1.0)以使其更加不稳定。