Tag Archives: Unity3D

Unity3D: Changing game speed and pausing

This article was originally posted on 4th August 2013 at Programmer’s Ranch using Unity3D 4.2.0f4. This updated version of the article uses Unity3D 5.3.4f1, and the source code is available at the Gigi Labs BitBucket repository. Syntax highlighting and a new screenshot have been added, and the text is slightly modified.

In this article, we’ll learn about controlling time in Unity3D. This allows us to easily pause the game, slow it down, or speed it up.

Create a new project and add a sphere to your scene via GameObject menu -> 3D Object -> Sphere. Next, create a new C# script by right clicking in the Project panel, and selecting Create -> C# Script. Name it Ball, and drag it onto your Sphere in the Hierarchy panel. Double-click the script to open it in Visual Studio.

We’re going to make a very basic bouncing ball just to be able to see the effects of our change in speed. Start off with the following code for the Ball script:

public class Ball : MonoBehaviour
{
    private Vector3 velocity;

    // Use this for initialization
    void Start()
    {
        this.velocity = new Vector3(1.0f, 1.0f, 0.0f);
    }

    // Update is called once per frame
    void Update()
    {
        this.transform.position += this.velocity * Time.deltaTime;

        if (this.transform.position.x > 5.0f)
            velocity.x = -velocity.x;
        else if (this.transform.position.x < -5.0f)
            velocity.x = -velocity.x;
        else if (this.transform.position.y > 6.0f)
            velocity.y = -velocity.y;
        else if (this.transform.position.y < -5.0f)
            velocity.y = -velocity.y;
    }
}

This will make the ball bounce when it reaches the sides of the screen. This may vary depending on your monitor so use whichever values work best.

unity3d-speed-ball

Games look interactive because they generate a certain number of images (frames) per second, usually something between 30 and 60. Time.deltaTime is the time between one frame and the next; multiplying this by the velocity makes the ball move pretty uniformly.

Another important property of the Time class is Time.timeScale. This is a measure of how quickly scripts and animations run, and is set to 1.0f by default. We can change this to make the game run at different speeds. To try it out, add the following code to the Ball script’s Update() method:

        if (Input.GetKeyDown(KeyCode.P))
            Time.timeScale = 0.0f;
        else if (Input.GetKeyDown(KeyCode.N))
            Time.timeScale = 1.0f;
        else if (Input.GetKeyDown(KeyCode.F))
            Time.timeScale = 2.0f;
        else if (Input.GetKeyDown(KeyCode.S))
            Time.timeScale = 0.5f;

What we’re doing here is:

  • If the player presses ‘P’ (pause), we set the time scale to zero, effectively stopping any movement in the game.
  • If the player presses ‘N’ (normal speed), we set the time scale to the default of 1.0f.
  • If the player presses ‘F’ (fast), we set the time scale to double the normal speed.
  • If the player presses ‘S’ (slow), we set the time scale to half the normal speed.

This simple property allows you to not only pause the game, but also to play the game at different speeds. Several games including Starcraft and Warcraft 2 have settings that allow you to tweak the game speed in order to make it more challenging or less frenetic.

starcraft-speed-settings

This article showed how a single line of code in Unity3D is enough to change the speed of a game or pause it. Although this was a very easy tutorial, I hope you will also find it very useful in any games you make!

Unity3D: Moving an Object with Keyboard Input

This is an updated version of the article originally posted on 24th May 2013 at Programmer’s Ranch. The original article used Unity 4.1.3f3, MonoDevelop, and 3D settings (2D in Unity didn’t exist back then), on Windows XP. This updated article uses Unity 5.2.2f1, Visual Studio 2015, and 2D settings, on Windows 10. Parts of the article have been rewritten, and syntax highlighting has been added.

The Unity3D game development engine has gained a lot of popularity in recent years. It supports various target operating systems, can be scripted in various languages, has a large community, and is always evolving. In this article, we’ll see how we can set up a simple project and have the player move an object by pressing the arrow keys on the keyboard.

The first thing you will need to do is to download and install Unity from their website. Once you’ve installed it and gone through the initial registration screens, you can opt to create a new project:

unity3d-input-startup

Click on the “New” button (shown in the image above). Here, you can choose the name and location of your new project, as well as whether to use 3D or 2D settings. For this particular article it doesn’t matter; the original article used 3D settings, while for this updated version I’ve done everything using 2D settings.

unity3d-input-newproject

Once you click “Create project“, your project will open in the Unity IDE.

From the GameObject menu, select 3D Object -> Cube to place a cube into the game world:

unity3d-input-create-cube

The cube will now be listed in the Hierarchy section – this section shows you a list of objects in your game world. You can also see the objects in the game world itself, in the left portion of the screen. If you click on the cube, you can see and manipulate its properties (e.g. position in the game world) in the Inspector:

unity3d-input-cube-properties

Right click on the Assets panel inside the Project section, and create a new C# script:

unity3d-input-create-cs-script

The script appears under Assets. Call the script “Movement“. Then, double-click the script to edit it. This will launch an external editor, probably MonoDevelop or Visual Studio:

unity3d-input-visual-studio

In the Update() method, add the following code:

if (Input.GetKeyDown(KeyCode.LeftArrow))
{
    Vector3 position = this.transform.position;
    position.x--;
    this.transform.position = position;
}

What are we doing here? In Unity, you can attach scripts to objects in order to make them do stuff. In our case, we will attach this script to the cube to be able to move it with the arrow keys.

The “this” in a Unity script refers to the object that the script is attached to (e.g. the cube). Each object has a transform property, which contains stuff like its position in the world. The position consists of a Vector3 which contains the x-, y- and z-coordinates of the object in the world.

The code above simply makes the object move left when the left arrow key is pressed, by varying the x-coordinate of the object’s position. While it would normally make sense to modify x directly, you can’t do that in Unity.

In the external editor, build the project to make sure it compiles (F8 in MonoDevelop, or Ctrl+Shift+B in Visual Studio). Then, switch back to Unity. Drag the Movement script onto the Cube object in the Hierarchy section. Once you click on the Cube in the Hierarchy section, you should see the Movement script in the Inspector:

unity3d-input-attached-script

Now, Press the Play button at the top of the Unity interface to start playing. The world view changes into an interactive rendering of the game:

unity3d-input-run-start

Test the game by pressing the Left Arrow key. Doing this should move the cube to the left:

unity3d-input-run-moved

Press the Play button again to stop the game. In the external editor, update the code to handle movement in all four directions:

if (Input.GetKeyDown(KeyCode.LeftArrow))
{
    Vector3 position = this.transform.position;
    position.x--;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
    Vector3 position = this.transform.position;
    position.x++;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
    Vector3 position = this.transform.position;
    position.y++;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
    Vector3 position = this.transform.position;
    position.y--;
    this.transform.position = position;
}

Press Play again in Unity to test it. Note that the cube returned to its original position. That is because each time you press Play, a new session is started with all objects having their default values.

So in this article, we have learned a few things about the Unity IDE, and we wrote a small script to move a cube in the game world. The intention was to get something working as quickly as possible, giving the reader a feel of working with Unity3D, while leaving details for other articles.