0

I started programming this pong game for CS class. I want to have the ball starting off in the center of the field so I used:

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

I want to make the game start once I press the space key. In order to do that I used:

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

However it does not work. Can someone please help me figure out what is wrong with my code? Please consider that this is not a JavaScript but a Processing question.

Here is my entire code so far:

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
 }
CodeMouse92
  • 6,840
  • 14
  • 73
  • 130
Abigail
  • 57
  • 8

1 Answers1

4

The answer to this question is the same as the answer to your other question: you need to store the state of your sketch in variables, then you need to draw each frame based on that state, and finally you need to change those variables to change the state of your game.

Here's a simple example that only draws an ellipse after you press a key:

boolean playing = false;

void keyPressed() {
  playing = true;
}

void draw() {

  background(0);

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

In this example, the playing variable is my state. I then update that state in the keyPressed() function, and I use that state to determine what I draw in my draw() function. You'll have to extrapolate a bit, but this process of breaking your problem down into a state, changing that state, and drawing that state is the answer to all of your questions.

Community
  • 1
  • 1
Kevin Workman
  • 41,537
  • 9
  • 68
  • 107