如何使图像水平弹跳?

时间:2011-10-03 04:25:36

标签: java panel awt runnable

我有一个水平移动的图像(“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();
    }
}

2 个答案:

答案 0 :(得分:2)

首先,你需要在一个字段中保持你的速度而不是硬编码:

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

答案 1 :(得分:1)

private int dx = 1;

public void cycle() {
    x += dx;
    y += 0;
    if (x+star.getWidth() >= getWidth()) {
        dx = -1;
    }
    if (x <= 0) {
        dx = 1;
    }
}