简体   繁体   English

如何使图像移动到随机位置?

[英]How can I make the image move in a random position?

I have an image inside the panel and it moves in a clockwise direction. 我在面板内部有一个图像,它沿顺时针方向移动。 Now, I want it to move in a random direction and that is my problem. 现在,我希望它朝随机方向移动,这就是我的问题。

Could someone give me an idea how to do it? 有人可以给我一个想法怎么做吗?

Here's what I've tried : 这是我尝试过的:

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;
        }
    }
}

Change 更改

y -= yVelocity;

To

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

Call a method like this to set a random direction: 调用这样的方法来设置随机方向:

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));
}

Just noticed that you're cycle method will need a little fixing for this to work. 刚刚注意到,您正在循环的方法将需要一些修复才能起作用。

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();
  }
}

(It works, but this is not the most efficient/elegant way to do it) (它有效,但这不是最有效/最优雅的方法)

And if you want some sort of 'random walk' try something like this: 如果您想进行某种“随机漫步”,请尝试以下操作:

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

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

You can increase 0.1 (max 1.0) to make it move more shaky. 您可以增加0.1 (最大1.0)以使其移动更不稳定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM