Wie man eine zufällige Richtung?

Habe ich ein Bild, das bewegt sich in eine zufällige Richtung, wenn es beginnt, zu schlagen die Wand. Das Bild fängt immer oder erscheinen in der linken oberen Ecke während der Ausführung, können Sie sehen, dass in meinem code. Jetzt möchte ich das Bild angezeigt wird, in eine willkürliche position während der Ausführung und das ist mein problem, könnte mir jemand eine Idee dazu? Vielen Dank im Voraus.

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

InformationsquelleAutor | 2011-11-01

Schreibe einen Kommentar