Gigi Labs

Please follow Gigi Labs for the latest articles. Programmer's Ranch no longer has its domain, so please update your bookmarks and links to programmersranch.blogspot.com.

Friday, June 7, 2013

Unity3D: Pong

Hi folks! :)

Today we're going to see how to create a game like Pong, one of the earliest classic arcade video games, using Unity3D. The approach for movement is very similar to the one we used in "C# Threading: Bouncing Ball", although we don't have to worry about threads in this case.

After creating a new project, use the GameObject -> Create Other menu to set up the scene using four cubes and a sphere. After scaling the cubes to be elongated, put one on each side: at the left and right as paddles, and at the top and bottom as walls that the ball can then bounce on:


One thing you'll notice is that the paddles don't look like straight lines - they are seen as if from the side. That's because we're using a perspective camera. For a game like Pong, where we don't care about perspective, an orthographic camera is probably better.

Select the Main Camera from the Hierarchy panel, and change the Projection property from Perspective to Orthographic. Change the Size property until the game objects fit the camera's view comfortably (check this by pressing Play in Unity, not from the camera preview, since the resolution is different):


Now, let's make the ball move. Right click in the Project panel and select Create -> C# Script. Name it Ball and drag it onto the Sphere. Double-click the script to open it in MonoDevelop.

Just like in "C# Threading: Bouncing Ball", we now give the ball a direction and a speed with which to move (Physics people will know they are together called velocity):

public class Ball : MonoBehaviour
{
    private Vector3 direction;
    private float speed;
 
    // Use this for initialization
    void Start ()
    {
        this.direction = new Vector3(1.0f, 1.0f).normalized;
        this.speed = 0.1f;
    }
 
    // Update is called once per frame
    void Update ()
    {
        this.transform.position += direction * speed;
    }
}

The normalized part is something we do for convenience. A normalised vector has a magnitude of 1, making it easy to work consistently with it. We then modify the speed using the speed variable.

In order to implement the bounce effect, we have the ball detect collisions, and change trajectory when a collision occurs:

    void OnCollisionEnter(Collision collision)
    {
        Vector3 normal = collision.contacts[0].normal;
        direction = Vector3.Reflect(direction, normal);
    }

Take a look at this diagram to understand what's happening here:


In order to make the ball bounce, we need to find where it hits a wall or paddle, and change its direction. We reflect the direction in the surface normal, which is at 90 degrees to the surface itself. In Unity, we get that surface normal from the point of contact with the surface, which is available from collision.contacts.

Although it is good to know the vector mathematics behind vector reflection, in Unity3D this is as easy as using Vector3.Reflect() and passing in the incident direction and the surface normal.

In order for this to work. You will need to add a rigidbody to the Sphere, via Component menu -> Physics -> Rigidbody.

Now, just add another script for the paddle movement, and attach it to the paddles:

public class Paddle : MonoBehaviour
{
    private float speed = 0.1f;
 
    // Use this for initialization
    void Start ()
    {
 
    }
 
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKey(KeyCode.UpArrow))
            this.transform.position += Vector3.up * speed;
        if (Input.GetKey(KeyCode.DownArrow))
            this.transform.position += Vector3.down * speed;
    }
}

Enjoy the game!


In this article, we created a simple Pong game and learned about orthographic vs perspective cameras as well as vector reflection (used to bounce an object off a wall).

This simple game mechanic can be used for various classic games including Pong and Arkanoid.

The only thing we didn't do is handle when the ball leaves the area, in which case the player should lose the game. I'll leave that as an exercise since it's quite trivial (you can do something like how we handle bullets in "Unity3D: Space Invaders (Part 4 - Collisions)", and when the ball leaves the area, you change to a different scene showing a loser's screen - see "Unity3D: Scenes and Building").

In the next article, we will revisit the bouncing ball theme and make an Arkanoid clone. So check back! :)

1 comment:

  1. Thanks for the tutorial. It's simple yet it includes exactly enough detail for a programmer who's never used Unity before.

    Note: I also had to uncheck the 'Use Gravity' box for the ball to work.

    ReplyDelete