我需要更改什么才能使代码工作?

时间:2016-05-09 19:15:20

标签: processing

我开始为CS课程编写这个pong游戏。我想让球从球场的中心开始,所以我使用了:

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

我想按空格键后开始游戏。为了做到这一点,我使用了:

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

然而它不起作用。有人可以帮我弄清楚我的代码有什么问题吗?请注意,这不是JavaScript,而是处理问题。

到目前为止,这是我的整个代码:

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
 }

1 个答案:

答案 0 :(得分: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()函数中绘制的内容。你需要进行一点推断,但是这个将问题分解为状态,改变状态并绘制状态的过程就是你所有问题的答案。

相关问题