我有一个图像在开始撞到墙上时会向随机方向移动。图像在执行过程中总是开始或出现在左上角,你可以在我的代码中看到。现在我希望图像在执行过程中出现在随机位置,这是我的问题,有人能给我一个想法吗?提前致谢。
public class Ball extends JPanel implements Runnable
{
private Image ball;
private Thread animator;
private int x, y;
private final int DELAY = 20;
private int speedX = 1;
private int speedY = 1;
private static final int RIGHT_WALL = 200;
private static final int LEFT_WALL = 1;
private static final int DOWN_WALL = 200;
private static final int UP_WALL = 1;
public Ball()
{
setBackground(Color.BLACK);
setDoubleBuffered(true);
ImageIcon ii = new ImageIcon(this.getClass().getResource("ball.gif"));
ball = ii.getImage();
x = y = 10;
}
public void addNotify()
{
super.addNotify();
animator = new Thread(this);
animator.start();
}
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 move()
{
x += speedX;
y += speedY;
if (x >= RIGHT_WALL)
{
x = RIGHT_WALL;
moveRandomDirection();
}
if (y > DOWN_WALL)
{
y = DOWN_WALL;
moveRandomDirection();
}
if (x <= LEFT_WALL)
{
x = LEFT_WALL;
moveRandomDirection();
}
if (y < UP_WALL)
{
y = UP_WALL;
moveRandomDirection();
}
}
public void moveRandomDirection()
{
double direction = Math.random() * 2.0 * Math.PI;
double speed = 10.0;
speedX = (int) (speed * Math.cos(direction));
speedY = (int) (speed * Math.sin(direction));
}
public void run()
{
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true)
{
move();
repaint();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - timeDiff;
if (sleep > 2)
{
sleep = 1;
}
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
}