gpt4 book ai didi

java - 如何让图像随机移动?

转载 作者:行者123 更新时间:2023-12-01 19:13:32 24 4
gpt4 key购买 nike

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

有人可以告诉我如何做吗?

这是我尝试过的:

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

最佳答案

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

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)以使其移动更加摇晃。

关于java - 如何让图像随机移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7633295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com