gpt4 book ai didi

java - 如何使图像水平反弹?

转载 作者:行者123 更新时间:2023-12-04 06:12:24 26 4
gpt4 key购买 nike

我有一个水平移动的图像(“ball.gif”),问题是当球到达面板尺寸的末端时如何让球反弹?我知道这并不难,但我只是对如何去做有点困惑。

有人可以帮我解决这个问题吗?

这是我迄今为止尝试过的:

public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(ball, x, y, this);
Toolkit.getDefaultToolkit().sync();

g.dispose();
}


public void cycle()
{



x += 1;
y += 0;
if (x >240)
{


x = 10;
y = 10;
}


}


public void run()
{

long beforeTime, elapsedTimeDiff, sleep;

beforeTime = System.currentTimeMillis();

while (true)
{

cycle();
repaint();

elapsedTimeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - elapsedTimeDiff;
System.out.println(sleep);

if (sleep < 0)
{
sleep = 2;
}
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
System.out.println("interrupted");
}

beforeTime = System.currentTimeMillis();
}
}

最佳答案

首先,您需要将速度保持在一个字段中,而不是对其进行硬编码:

private static final int RIGHT_WALL = 240;
private int x, y;
private int xVelocity = 1;


//...
x += xVelocity;
y += 0; //change this later!

然后当你做边界检查时,翻转你的 xVelocity :
//...
if ( x > RIGHT_WALL ) {
x = RIGHT_WALL;
xVelocity *= -1;
}

关于java - 如何使图像水平反弹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631018/

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