开发者

How to make the image bounce horizontally?

I have an image("ball.gif") that moves horizontally, the problem is how could I make the ball bounce when it reach the end of the size of the panel? I know this is not really difficult but I'm just a little bit confuse on how to do it.

Could someone help me about this matter?

This what I've tried so far :

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


First, you need to hold your velocity in a field instead of hardcoding it:

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


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

Then when you do your bounds checking, flip your xVelocity:

//...
if ( x > RIGHT_WALL ) {
   x = RIGHT_WALL;
   xVelocity *= -1;
}


private int dx = 1;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜