Tag Archives: keyboard

Moving the player in a 2D game with Unity and C# code

This video explains how to move your player in a 2D game in Unity with C# code. After watching this video, you will be able to move your player left and right in a scene using keyboard input.

Watch the video below and scroll down to see the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }
  }
}

Next tutorial: Making the player jump with C# code

Moving an object with force in PlayCanvas

This tutorial explains how to use keyboard input to move an object around. But rather than telling the object how far it needs to move (like in this other tutorial), we will apply force to the object instead. This means that the object your moving can also hit other objects and interact with them rather than just going through them.

Step 1 – Setting up the object you want to move

To begin with, you need to create an object or use a model that you want to move. Then you need to add a Rigid Body component and a Collision component so that this object can collide and interact with other objects in the scene. For this example, I have added a Box entity (click + in the Hierarchy and then click Box) but you can use another 3D shape or model.

3dobject
Then you need to select the object and click on Add Component (in the Inspector panel on the left side of the screen) and choose the Collision component. If you have a box shape (entity) then you should set the Collision Type to Box (if you have a sphere shape, then select Sphere for Type, and so on).

Match your collision settings up so they look like the settings shown below. The numbers in the Half Extents property boxes should be half the numbers in the Scale property boxes above it. Eg. if the scale X property of the box has a value of 4 then the Half Extents X value should be 2.

box_collision

Now click on Add Component again and this time add the Rigid Body component. Change the Type to Dynamic and modify the values so they are the same as those below (experiment with these values later to get the effect you want).

rigid_body
It is important to make sure any other objects that this object will interact with also have Rigid Body and Collision components attached to them. For example, if you don’t want this object to fall through your ground in the scene, then the ground object should have a Static type Rigid Body and a Collision component.

If you want other objects to not be moved by this object, they should have a Static type Rigid Body and Collision component. Otherwise, if you want this object to move other objects when it touches them, add Dynamic type Rigid Body and Collision components to those other objects.

Adding a script to the object

Click on + in the Assets panel and choose Script to create a new script.

create_script
Call the new script moveWithForce.js and hit Enter to create the script.

script_name

Now you need to attach the script to the 3D object or model you want to move or control. Select the 3D object (eg. box) and then click on Add Component and select Script. Drag the moveWithForce.js script onto the Scripts component on the object in the Inspector panel and then let go. The script should now be attached to the object.

script_attached

 

Writing the code

Double-click on the moveWithForce.js script you just created in the Assets panel and replace all of the existing code with the following code in the Code Editor window:

// Add this code to any object you want to move with force
// Object that this script is attached to must have collision component and DYNAMIC rigid body component

pc.script.attribute("power", "number", 1000);  // set power to initial value of 1000
pc.script.create('moveWithForce', function (app) {
    // create force variable
    var force = new pc.Vec3();
    // Creates a new MoveWithForce instance
    var MoveWithForce = function (entity) {
        this.entity = entity;
    };

    MoveWithForce.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            // Check for required components
            if (!this.entity.collision) {
                console.error("First Person Movement script needs to have a 'collision' component");
            }
            
            if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
                console.error("First Person Movement script needs to have a DYNAMIC 'rigidbody' component");
            }
            
            // Listen for keyboard press events
            app.keyboard.on(pc.EVENT_KEYDOWN, this._onKeyDown, this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {

            // movement
            var x = 0;
            var z = 0;
            var y = 0;
            
            // Use W-A-S-D keys to move player around and Space to make player jump
            // Check for key presses
            if (app.keyboard.isPressed(pc.KEY_LEFT)) {
                x -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
                x += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_UP)) {
                z -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_DOWN)) {
                z += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_SPACE)) {
                console.log("space pressed");
                y += 0.05;
            }
            
            // use direction from keypresses to apply a force to the character (x and z axes)
            if (z !== 0) {
                force.set(0, 0, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            if (x !== 0) {
                force.set(x, 0, 0).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            // use direction from keypresses to apply a force to the character (y axis)
            if (y !== 0) {
                force.set(x, y, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
        },
        
        _onKeyDown: function (event) {
            // When the space bar is pressed this scrolls the window.
            // Calling preventDefault() on the original browser event stops this.
            event.event.preventDefault();
            console.log("Scrolling disabled");
        }
    };

    return MoveWithForce;
});

Now click on Save and then go back to the game Editor window. That’s it! Launch your game by clicking on the Launch (play) button and you should now be able to control the 3D object/model by using the keyboard to move it around and make it jump. The code is set up to move the object using the arrow keys and space bar to jump. However, you can change these keys and you can also remove the code that makes the object jump if you don’t want to make it jump in the game.

 

 

 

Moving objects with keyboard input in PlayCanvas

If you watched the previous tutorial you would have learned how to make an object move on its own using JavaScript code. In this tutorial, we will make an object move around using keyboard input. That is, if the left arrow key is pressed on the keyboard then we can make the object move left. If the right arrow key is pressed on the keyboard then we can make the object move right, and so on…

Keyboard input will be very useful in your games eg. to make a player jump, to move around, pick up objects or enter your name in the high score book! Watch the video to find out how to add keyboard input to your games and then try out the sample code further down the page.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script.

In the code, you will see app.keyboard.isPressed – this will check if the key is being pressed during the current frame. If you hold down the key, the object will keep moving. If you use another method called app.keyboard.wasPressed instead it will only check if the key was pressed in the current frame (it will detect one keypress and won’t keep the object moving when you hold the key down).

pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 if(app.keyboard.isPressed(pc.input.KEY_RIGHT)){
 this.entity.translateLocal(0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_LEFT)){
 this.entity.translateLocal(-0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_UP)){
 this.entity.translateLocal(0,0.1,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_DOWN)){
 this.entity.translateLocal(0,-0.1,0);
 }
 }
 };
 
 return Move;
});

Transforming objects using scripts

This video tutorial will show you how to transform objects (move, rotate, scale) in your Unity game using C# scripts and also how to implement player interaction with the game by allowing players to transform objects using keypresses on their keyboard.

Watch the video below and then scroll down to see the sample code.

Here is some sample code with different object transformations assigned to different keypresses on the keyboard. You can change the transformations and assigned keys although it is a good idea to use the input manager rather than specific keypress detection so that your players have the option of remapping keys to suit their own preferences.

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 if (Input.GetKey (KeyCode.W)) {
 transform.Translate (0f,0f,0.1f);
 }
 if (Input.GetKey (KeyCode.S)) {
 transform.Translate (0f,0f,-0.1f);
 }
 
 if (Input.GetKey (KeyCode.D)) {
 transform.Translate (0.1f,0f,0f);
 }
 if (Input.GetKey (KeyCode.A)) {
 transform.Translate (-0.1f,0f,0f);
 }
 
 if (Input.GetKey (KeyCode.Z)) {
 transform.Rotate (0f,1f,0f);
 }
 
 if (Input.GetKey (KeyCode.X)) {
 transform.Rotate (0f,-1f,0f);
 }
 
 if (Input.GetKey (KeyCode.C)) {
 transform.localScale = new Vector3(1f,1f,1f);
 }
 
 if (Input.GetKey (KeyCode.V)) {
 transform.localScale = new Vector3(5f,5f,5f);
 }
 
 }
}

Note: If you find that the values for x, y and z axes seem to work the opposite to what you expect, it might be because you have the camera at a different angle. For example, if your camera is on the opposite side of your object, then pressing the key that is meant to move the object left might actually move it to the right.

Now try using variables to store the values for speed, eg:

using UnityEngine;
using System.Collections;
 
public class move : MonoBehaviour {
 
 public float turnSpeed = 5.0f;
 public float forwardSpeed = 0.25f;
 
 // Update is called once per frame
 void Update () {
 transform.Rotate(turnSpeed, 0.0f, 0.0f);
 transform.Translate(0.0f, 0.0f, forwardSpeed);
 }
}

Here is another method of moving objects on their own at a steady speed (this example does not include keyboard input).

using UnityEngine;
using System.Collections;
 
public class moveCube : MonoBehaviour {
 
 public float speed = 1.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 transform.Translate (Vector3.forward * speed * Time.deltaTime);
 // This will move the cube forward on its own at steady speed
 // Vector3 is for 3D , Vector2 is for 2D
 // You can change Vector3.forward to Vector3.back, Vector3.left, or Vector3.right
 
 
 }
}

Keyboard input in Unity

In Unity, you can set up your game to detect specific keypresses and then react to those keypresses. However, there is a better way of setting up input using Unity’s built-in Input Manager.

The video below will show how to use the Input Manager and how to also detect specific keypresses in your game. After you’ve finished watching the video, scroll down to see the sample code.

Input Manager

Setting up your game to detect specific keypresses doesn’t allow players to remap the game input controls to suit their preferences. However, if you use the Input Manager you can allow the player to map the controls to their own liking or use the defaults (eg. the W, A, S and D keys).

You can set up controls for each of the different axes in the Input Manager by clicking Edit > Project Settings > Input. Then you can write a script using the GetAxis() method to detect key presses.

Below is some sample code that will display horizontal and vertical movement in the console when the W, A, S and D keys (or arrow keys) are pressed. Simply place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

float horizontalValue = Input.GetAxis("Horizontal");
float verticalValue = Input.GetAxis("Vertical");
 
if (horizontalValue != 0)
{
 print("Horizontal movement: " + horizontalValue);
}
 
if(verticalValue != 0)
{
 print("Vertical movement: " + verticalValue);
}

Save the script and then run the scene. Check the output in the console after pressing the W, A, S and D keys and the arrow keys.

Try out the code above and see what happens when you press the W, A, S and D keys or arrows keys on your keyboard. Also, did you notice how the sentences and values are combined in the print statements above? This is an example of concatenation (where strings are joined together).

Specific key input

Although it is generally a good idea to use the Input Manager for key input detection, it may sometimes be necessary to check whether a specific key has been pressed by the user. To do this, you can use the GetKey() method. This method will read a keycode which corresponds to a specific key on the keyboard. It will then return either a true or false value depending on whether the key is pressed or not.

As an example, to check if the A key is being pressed, you can use the following code. Just place this code inside the Update() method in a script that is attached to an object inside your game’s scene (eg. the Main Camera object).

bool isKeyDown = Input.GetKey(KeyCode.A);

Tip: In MonoDevelop, if you are not sure what keycode corresponds to a key, you can begin typing in the name of the KeyCode object followed by a period. A popup menu should appear, showing you all of the possible choices. This automatic popup feature in MonoDevelop can be used for many other objects/methods too and is pretty handy.

You can use a simple if statement to specify an action to occur when a keypress is detected. For example, the following code will output a message to the console saying that the ‘A’ key has been pressed when it is detected that the ‘A’ key has been pressed.

if(Input.GetKey(KeyCode.A))
{
 print("You pressed the 'A' key.");
}

Save the script and then run the scene. Check the output in the console after pressing the ‘A’ key.

Unity Keyboard Shortcuts

This page provides some of the keyboard shortcuts you can use to work faster in Unity. More keyboard shortcuts can be found on the Unity website.

Function Windows keyboard combination Mac keyboard combination
 Save  Ctrl + S  Command + S
 Undo  Ctrl + Z  Command + Z
 Redo  Ctrl + Y  Shift + Command + Z
 Pan  Q  Q
 Move  W  W
 Rotate  E  E
 Scale  R  R
 Snap  Ctrl + Left Mouse  Button  Command + Left  Mouse Button
 Vertex Snap  P  P
 Play  Ctrl + P  Command + P
 Pause  Ctrl + Shift + P  Command + Shift + P
 Step  Ctrl + Alt + P  Alt + Command + P
 Frame (centre)  selection  F  F
 Refresh  Ctrl + R  Command + R
 Duplicate  Ctrl + D  Command + D

Keyboard events in JavaScript

In earlier JavaScript tutorials we looked at using onclick and onmouseover events to call a function when a user clicked or rolled their mouse over a button, and also the onload event to start an animation when a page had loaded. We can also use keyboard events such as when a key has been pressed on the keyboard.

Watch the video below which demonstrates how to use keyboard events, and then scroll down to see the sample code.

There are three different types of keyboard events we are using:

  • keydown
  • keypress
  • keyup

A keydown event is triggered when a button on the keyboard has been pressed down. A keyup event is triggered when a button that has been pressed on the keyboard is released. These events use keycodes to represent the many letters, numbers and other keys available. A keycode is returned to the program when a button has been pressed. You can find a list of keycodes here.

A keypress event is only triggered when you click on a key that represents a character such as a letter or number. A keypress event will tell the program what character the key represents, while the keydown and keyup events only tell the program what key has been pressed or released.

Keydown and keyup events will not tell the program if a letter key that was pressed is uppercase or lowercase. However, if you use the keypress event, then a program could detect when the Shift button and a character key were pressed to make an uppercase letter or another character (eg. Shift + p = P key, and Shift + 5 = % key).

The keydown and keyup events only trigger once when a key is pressed. Another thing to note is that keycodes return a number which represents a key pressed, and they work with keydown and keyup events, while ASCII codes return an ASCII code and work with keypress events. This link shows both the keycodes and ASCII codes that represent different keys.

The code below shows how to use a keydown event and a keycode of 65 to detect when the ‘a’ letter key is pressed on the keyboard. If the ‘a’ key is pressed, then an alert message is displayed.

<html>
 
<head>
<title>Key press events</title>
<script>
 
window.addEventListener("keydown", checkKeyPress, false);
// The parameters of the event listener are event, function to run, useCapture (optional).
// This event listener runs checkKeyPress function when a key is pressed down
// You can use keydown or keyup to check what key has been pressed or released
 
 
// this function checks to see if the letter 'a' key has been pressed
function checkKeyPress(key) {
 if (key.keyCode == "65") {
 alert("The 'a' letter key has been pressed.");
 // 65 is the keycode that is returned when the 'a' letter key is pressed
 // if you use keypress event instead of keydown/up then you must use ASCII code instead of keycode
 }
}
 
</script>
</head>
 
<body>
 <p>Press the 'a' key to see the alert message<p>
</body>
 
</html>

Try it yourself

Try the above code and then use the keyup event instead to see what happens. Change the keycode in the ‘if’ statement to test other key presses, and then try using the keypress event with ASCII codes. Also try using canvas.addEventListener in a canvas instead of window.AddEventListener.

Hints

As an example, the letter ‘a‘ key is represented by the keycode of 65 using a keydown or keyup event and does not distinguish between upper and lowercase. If you use a keypress event, then you will need to use the ASCII code of 65 to check for uppercase A and 97 for lowercase a. For more information about the different keyboard events and how key codes work, click here. Note that some keys are not compatible with keyboard events in certain browsers. You can check out compatibility of browsers here.

A note about the addEventListener method

The useCapture parameter in the addEventListener method is optional. If used, it must be a boolean value. The boolean value will specify whether the event being used should be executed during the bubbling or capturing phase. A boolean value of true  means the event handler is executed during the capturing phase, while false (default option) means that the event handler is executed during the bubbling phase. To find out more about bubbling and capturing, click here.