2011-10-03 96 views
2

我有一個水平移動的圖像(「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

首先,你需要保持在你的領域,而不是速度是硬編碼的:當你做你的邊界檢查

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

是啊.. tnx,它的工作原理.. ;-) – sack

1
private int dx = 1; 

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