2013-06-11 20 views
1

我目前正試圖教自己在Java中的代碼,我使用eclipse和我有一個教程創建pong,但一些它是如何失蹤。我遇到麻煩的唯一部分是完成球類。我已經把它渲染並正確顯示在窗口中,但實際上並沒有做任何簡單的靜止。這是因爲我不知道我需要什麼代碼,並且所有的谷歌搜索都導致了代碼無法工作的挫敗感。使用eclipse編程傍

這是我迄今在球類中所有的。

import java.awt.Color; 
import java.awt.Graphics; 


public class Ball extends Entity { 

public Ball(int x, int y, Color color) { 
    super(x, y, color); 
    this.width = 15; 
    this.height = 15; 
    int yspeed = 1; 
    int xspeed = 2; 
} 

public void render(Graphics g) { 
    super.render(g); 
} 




public void update() { 
    if (y <= 0) { 
     y = 0; 
    } 

    if (y >= window.HEIGHT - height - 32) { 
     y = window.HEIGHT - height -32; 
    } 
} 

任何意見將不勝感激。

+0

在更新函數中需要一些代碼來改變球的位置(例如根據其速度) –

回答

3

到目前爲止,你的球類看起來不錯,你寫的(或從教程中複製的)。您錯過了將「生活」置於其中的代碼,例如這使球移動。您有一些字段,例如xspeedyspeed,但沒有代碼實際將增量從一個時間單位應用到另一個時間單位。在(我希望)定期調用update()方法都應該值適用於xy領域:

public void update() { 
    x += xspeed; 
    y += yspeed; 

    if (y <= 0) { 
     y = 0; 
    } 

    if (y >= window.HEIGHT - height - 32) { 
     y = window.HEIGHT - height -32; 
    } 
} 

這就是你所需要的爲update一部分。 下一件大事就是實施邏輯當球擊中牆壁或槳時發生的事情。對於這樣的事件,您需要操縱xspeedyspeed變量。

0

明顯的步驟將是:

public void update() { 
    x += xspeed; 
    y += yspeed; 

    if (y <= 0) { 
     y = 0; 
    } 

    if (y >= window.HEIGHT - height - 32) { 
     y = window.HEIGHT - height -32; 
    } 

    // TODO: Code to change the direction of the ball (i.e. xspeed and yspeed) 
    // when it hits a wall or paddle. 
} 

而且你一定不要忘記調用update()你叫render()之前。