2016-05-09 105 views
0

我開始編寫CS類的pong遊戲。我想有球在場地中央開始關閉,因此我用:我需要更改哪些代碼才能使用代碼?

ellipse (width/2, height/2, 15, 15); 

我想打比賽開始後我按空格鍵。爲了做到這一點,我用:

if (keyPressed == true) {ellipse (ballX, ballY, 15, 15); fill (0, 255, 0);} 

但它不起作用。有人可以幫我弄清楚我的代碼有什麼問題嗎?請考慮這不是一個JavaScript,而是一個Processing問題。

這是到目前爲止,我整個代碼:

float ballX = 15, ballY = 15, dX = 15, dY = 15; // variables for the ball 
float paddleX; // variables for the paddles 
int mouseY; // variable to make the pong move with the mouse movement 
boolean key, keyPressed; 

void setup() { 
    size (1500,1100); // the field is going to be 1500x110px big 
    paddleX = width - 40; 
    ballX = 15; ballY = 15; 
} 

void draw() { 
    background(0); // black background 

    ellipse (width/2, height/2, 15, 15); // this is the starting point of the ball 

    if (keyPressed == true) { ellipse (ballX, ballY, 15, 15); fill (0, 255, 0); } // the game will only start when a key is pressed 

    if (ballX > width || ballX < 0) { dX = -dX; } // if the ball reaches the right or left wall it will switch directions 
    if (ballY > height || ballY < 0) { dY = -dY; }// if the ball reaches the upper or lower wall it will switch directions 

    ballX = ballX + dX; ballY = ballY + dY; // the ball with move with the speed set as dX and dY 

    rect(paddleX/58, mouseY, 20, 100); fill (255,10,20); // green pong 
    rect(paddleX, mouseY, 20, 100); fill (60,255,0); // red pong 
} 
+0

你需要一個actionListener來做到這一點.. – ryekayo

+0

@Ryekayo這是處理。這已經嵌入到keyPressed方法中。 – DarmaniLink

+0

這是你寫的所有代碼嗎? – FedeWar

回答

4

的這個問題的答案是一樣的答案your other question:你需要存儲在變量草圖的狀態,那麼你需要根據該狀態繪製每一幀,最後你需要改變這些變量來改變你的遊戲狀態。

這裏有一個簡單的例子,僅繪製橢圓你按下一個鍵後:

boolean playing = false; 

void keyPressed() { 
    playing = true; 
} 

void draw() { 

    background(0); 

    if (playing) { 
    ellipse(width/2, height/2, 50, 50); 
    } 
} 

在這個例子中,playing變量是我狀態。然後我在keyPressed()函數中更新該狀態,並使用該狀態來確定我在draw()函數中繪製的內容。你必須推斷一下,但是這個把你的問題分解成一個狀態,改變狀態和繪製狀態的過程就是你所有問題的答案。

相關問題