Unity/Futile Pong Example (Part 5) – Adding some ball movement and managing input for our Pong game in Futile

By the end of this tutorial, you should have something that looks like this. You can download the Assets folder for this tutorial here.

In the last tutorial, we created a framework for the various objects in our game. There are two paddles, a ball, and a game manager. Let’s see if we can get the ball moving along with our paddles.

Let’s start with our ball, which currently spawns in the middle of the screen and just sits there. There are a few ways to handle the ball’s movement. Instead of assigning an angle to our ball, I will be using velocityX and velocityY. One of the reasons for this is because it will make it really easy later on to handle collisions with the the walls, where we can simply reverse the sign of the velocities. We’ll get to that part later.

In our PDBall.cs file, replace the contents with the code below.

using UnityEngine;
using System.Collections;
 
public class PDBall : FSprite {
	public float xVelocity;
	public float yVelocity;
	public float defaultVelocity;
	public float currentVelocity;
	
    public PDBall() : base("ball") {
		defaultVelocity = 100.0f;
		currentVelocity = defaultVelocity;
    }
}

In addition to velocities for x and y, we will also utilize a default velocity and current velocity just in case we want to increase or decrease the speed of the ball during gameplay later on. We’ll set the default velocity to 100.0f, which will essentially be equivalent to 100 points per second. We can adjust this later if it is too fast or slow.

In our PDGame.cs file, we have a function to reset our ball already in place. Let’s replace it with the code below

    public void ResetBall() {
        ball.x = 0; // Place ball in the center of the screen
        ball.y = 0;
		
		// Ensure that the ball starts at a random angle that is never greater than 45 degrees from 0 in either direction
		ball.yVelocity = (ball.defaultVelocity/2) - (RXRandom.Float() * ball.defaultVelocity);
		// Make sure that the defaultVelocity (hypotenuse) is honored by setting the xVelocity accordingly, then choose a random horizontal direction
		ball.xVelocity = Mathf.Sqrt((ball.defaultVelocity*ball.defaultVelocity) - (ball.yVelocity*ball.yVelocity)) * (RXRandom.Int(2) * 2 - 1);
    }

Don’t be too freaked out by this change. It isn’t all that important if you understand it. Simply put we don’t want the ball to start off traveling straight up, or any angle close to it because it would make for a slow start, so I limit the angle by limiting the vertical velocity.

Also in PDGame.cs, let’s add an Update() function to our PDGame class, which will be called once per frame.

	public void Update(float dt) {
		// Integrate to find the new x and y values for the ball
		float newBallX = ball.x + dt * ball.xVelocity;
		float newBallY = ball.y + dt * ball.yVelocity;
		
		// Render the ball at its new location
		ball.x = newBallX;
		ball.y = newBallY;
	}

The Update function is going to receive delta time (dt) as a parameter from the Update() function in PongGame.cs. Technically speaking, Time.deltaTime does not need to be passed to our Update function since it is a static variable for the globally accessible Time class, but it doesn’t hurt either. We’ll utilize basic Euler integration to calculate our new ball positions, just to keep it simple. Feel free to utilize RK4 or Verlet.

Finally, back in our PongGame.cs file, let’s change our Update function to reflect the code below.

    // Update is called once per frame
    void Update () {
		game.Update(Time.deltaTime);
    }

Execute the code, and our ball should head in a random direction at a velocity of 100 points per second. This will be useful whenever a point is scored and we want to reset the ball. Unfortunately, for now our ball is just going to float away indefinitely.

I would like to focus on handling input before worrying about the ball’s collision detection. In fact, we won’t handle collision detection until the next tutorial, so we’ll fix our lost ball then.

In your PDPaddle.cs file, replace it with the code below.

using UnityEngine;
using System.Collections;
 
public class PDPaddle : FSprite {
    public string name;				// Since paddles are essentially our players, we'll give them a name to display later.
    public int score;				// Our player's current score
	public float defaultVelocity;	// Default velocity
	public float currentVelocity;		// Current maximum velocity
     
    public PDPaddle(string name) : base("paddle")  { // Constructor for our paddle
        this.name = name;			// Set our _name variable to the value passed in the constructor
		
		defaultVelocity = Futile.screen.height; // Our paddle will be able to traverse the height of our screen in 1 second, seems reasonable.
		currentVelocity = defaultVelocity;
    }
}

Just like our PDBall, I want to set a default and current velocity, which will reflect the speed at which they move vertically. By doing this, we can do fun things later on like give one player the ability to slow down the other player, or speed himself up, or even have power ups that the ball can collide with which will do the same.

In PDGame.cs, change the Update() function of the PDGame class to reflect the code below.

	public void Update(float dt) {
		float newPlayer1Y = player1.y;
		float newPlayer2Y = player2.y;
		
		// Handle Input
		if (Input.GetKey("w")) { newPlayer1Y += dt * player1.currentVelocity; }
		if (Input.GetKey("s")) { newPlayer1Y -= dt * player1.currentVelocity; }
		if (Input.GetKey("up")) { newPlayer2Y += dt * player2.currentVelocity; }
		if (Input.GetKey("down")) { newPlayer2Y -= dt * player2.currentVelocity; }
		
		// Integrate to find the new x and y values for the ball
		float newBallX = ball.x + dt * ball.xVelocity;
		float newBallY = ball.y + dt * ball.yVelocity;
		
		// Render the ball at its new location
		ball.x = newBallX;
		ball.y = newBallY;
		player1.y = newPlayer1Y;
		player2.y = newPlayer2Y;
	}

Note that player1 is controlled by w and s, and player2 is controlled by the up and down arrows. I’m not sure if I will cover AI yet, so for now both paddles will be controlled manually.

Execute the code, and you should be able to control both paddles.

As of now, our ball will rip straight through the paddles. Collision detection is going to be the focus of the next tutorial.

Take me to the next tutorial!

By the end of this tutorial you just read, you should have something that looks like this. You can download the Assets folder for this tutorial here.

About these ads

7 thoughts on “Unity/Futile Pong Example (Part 5) – Adding some ball movement and managing input for our Pong game in Futile

  1. Pingback: Creating the basic structure of our Pong game in Futile | Game Development

  2. Just a typo heads up, after calling the game.Update function you say, “In your PongDemo.cs file, replace it with the code below.” This should say PDPaddle.cs.

    Great tutorial so far. I’ll be looking forward to future updates.

  3. Pingback: Unity/Futile Tutorial Part 6 – Adding collision detection to our Pong game | Game Development

  4. Pingback: Planning Pong | skylergame101

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s