Pong
Lately I have been overwhelmed with
my current project so I thought it would be a good time to take a step back and
do something simple. For anyone who doesn’t know, pong is basically a
simulated table-tennis game. It was one of the first video games, so I thought
it would be a good place to start this blog.
I decided to use Unity to make the
game. The coding for it was all pretty simple. The ball has a variable for its
speed in the x and y direction. Every frame it calls a function that increments its current position by these variables.
There are six surfaces the ball can hit. These are the top wall, bottom wall, right wall, left wall, and one of the two paddles. If it hits the left or right wall that is a score and the game resets. If it hits the top wall, bottom wall, or one of the paddles it bounces off and goes in the opposite direction. I did this by reversing the perpendicular speed variable. For example, if it hits the top or bottom wall the y speed is reversed and if it hits a paddle the x speed is reversed.
The balls x speed is reversed after hitting the paddle |
To make the game more interesting, if the paddle is moving up it increases the balls y speed and if it is moving down it decreases it. I handled all of these collision rules with tags. Every surface has a different tag that gets returned when the ball collides with it. A switch statement then uses the returned tag to determine what to do.
I programmed one paddle to be controllable by the player
and the other to be controlled by a simple AI. The x speed of the ball is
always going to equal the absolute value of whatever you set it to since the
only thing that changes is the direction. The y speed on the other hand will
become slower and faster since it will change when it hits a moving paddle. The AI paddle will only follow the ball, it cannot predict if it is going
to bounce off the top or bottom. If you increase the y speed enough and hit the
ball towards a wall the AI paddle will move towards the wall and not be
able to catch the ball when it bounces off and you will win the round.
I embedded the game below for you to try. You will need to download the Unity web player and give it permission to run. Don't worry its safe, quick and easy. When you get the game running move the paddle up and down with the W and S key. Press space to start a round.
Comments
Post a Comment