2012-06-30 54 views
0

我的目標是讓球以槳爲中心,即使球的半徑值在未來版本的遊戲中發生變化。 我唯一的問題是對遊戲球的x座標執行正確的數學公式 。我得到了完美的y座標公式。突圍(遊戲項目) - 讓球將球對準槳--Java

我不需要正確的答案。我只需要指導和建議就可以得到答案。

這裏是java程序的圖片:

http://i33.photobucket.com/albums/d86/warnexus/ball.png

您可以找到註釋下面的代碼「//麻煩搞清楚這裏的數學」。

/** Radius of the ball in pixels */ 
private static final int BALL_RADIUS = 500; 


private void setup_Paddle() 
{ 
    // TODO Auto-generated method stub 

    // x coordinate of the upper left corner 
    // y coordinate of the upper left corner 

    paddle = new GRect(20,20,PADDLE_WIDTH,PADDLE_HEIGHT); 
    paddle.setFilled(true); 
    paddle.setColor(Color.PINK); 
    add(paddle,paddleInitialLocationX,paddleInitialLocationY); 

} 

private void setup_Ball() 
{ 

    // Trouble figuring the math here 
    int ballSetUpCoordX = (int) (paddle.getX()); 
    // Good Code! 
    int ballSetUpCoordY = (int) (paddle.getY()-BALL_RADIUS); 

    gameBall = new GOval(BALL_RADIUS,BALL_RADIUS); 
    gameBall.setFilled(true); 
    gameBall.setColor(Color.BLUE); 

    add(gameBall,ballSetUpCoordX,ballSetUpCoordY); 
} 

    private GOval gameBall; 
    private GRect paddle; 
    private int paddleInitialLocationX = 200; 
    private int paddleInitialLocationY = 500; 

回答

2

座標一般用於物體的左上角。因此,要讓任何兩個對象o1o2居中在同一地點,您必須根據大小進行偏移。

在這裏,我們將o1的中心移動到o2的中心。

int o2CenterX = o2.x - (o2.width/2); 
//If we just used o2CenterX, it would put the corner of o1 into the center of o2 
o1.x = o2CenterX - (o1.width/2); 

重複y,你似乎已經完成(半徑作爲寬度/ 2)。除非想讓槳和球在屏幕上相交,否則您可能必須稍微調整此公式。

+0

我試過你說的,但它似乎不正確,除非我編寫它錯了:\t int center =(int)(paddle.getX() - (PADDLE_WIDTH/2)); \t \t int ballSetUpCoordX =(int)(center - (PADDLE_WIDTH)/ 2); – Nicholas

+0

它仍然是一個很好的建議,我會投票評論,但我需要4個更多的代表。 – Nicholas

+0

你有第二行錯誤。它需要被球寬度抵消。 – Thomas