I’ve build a single-player pong game with the JavaScript library p5.js. It’s a simple game with a rectangle, an ellipse, and a little animation.
The draw function runs over and over again, animating the screen. By continuously updating the x- and y-coordinates of an object in the draw function. The 400x400 canvas was a little limiting, so I’ve updated the setup function to span over the whole window.
The ball is an ellipse whose coordinate points we update over and over again, so that it moves and I had to constantly changing the x- and y-coordinates of the ball to animate it, so it would be better to store those in variables. I’ve also did some calculations with the width and height (=diameter) of the ball.
xBall starts off the ball with a random x-coordinate between 50 and 350. yBall starts off the ball with a default y-coordinate of 50. The diameter is also set to 30. The ball moves to a random location near the top, but everything else should be the same.
First, I needed to track the speed at which the ball changes x- and y-coordinates. After I set the background in the draw function. After, I’ve changed the ball’s location, incrementing its x- and y-coordinates by the xBallChange and yBallChange values. So that the ball can move. Than I needed to make the ball detect when it is hitting the walls.
if ((xBall > xPaddle && xBall < xPaddle + paddleWidth) && (yBall + (diameter/2) >= yPaddle)) { xBallChange *= -1; yBallChange *= -1;}
This code on the side checks to see if the ball’s x-coordinate is between 0 and windowWidth, and if the ball’s y-coordinate is between 0 and windowHeight. If the coordinates are outside those ranges, the ball has hit a wall. When the ball collides with the wall, it can go in the opposite direction if you make the coordinate change go from positive to negative, or vice versa. You can see in the code that xBallChange and yBallChange are multiplied by -1 to achieve this effect.
Later, I’ve added a paddle by defining some variables to it. Then, I’ve added an if statement that “If the game has not yet started, the paddle is placed at the middle of the window about 100px above the bottom of the screen. Since started is then declared true, this code never runs again”.
Lastly, to make the paddle controlled by the right and left arrow keys, we simply I’ve add ed a third function called keyPressed() which allows to adjust the paddle’s x-coordinates by incrementing or decrementing the xPaddle variable.
I’ve also added a score. Every time the ball collides with the paddle, it increase the score by one. (score++). But, the game has still have a bug in collision. I couldn’t figured it yet.
You can reach the code from;