Take control of your scene with this simple yet effective way to move objects with keyboard input!

Unity Quick Tips: Moving an Object with Keyboard Input

Part 6 of Our Bite-Sized Unity Tips and Tricks for Beginners

James West
3 min readFeb 18

Welcome to Part 6 of our series of bite-sized Unity tips and tricks for beginners! In this article, we’re going to show you how to move an object using keyboard input in Unity. Whether you’re creating a game or another application, moving objects with keyboard input is a great way to add interactivity and control to your scene. For this example we will be using the legacy Input system.

Here’s the code sample:

using UnityEngine;

public class MoveObject : MonoBehaviour
{
public float speed = 5f;

private void Update()
{
if (Input.GetKey(KeyCode.RightArrow))
{
transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
}

if (Input.GetKey(KeyCode.LeftArrow))
{
transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f);
}

if (Input.GetKey(KeyCode.UpArrow))
{
transform.position += new Vector3(0f, speed * Time.deltaTime, 0f);
}

if (Input.GetKey(KeyCode.DownArrow))
{
transform.position -= new Vector3(0f, speed * Time.deltaTime, 0f);
}
}
}

In this script, we use the Input.GetKey method to check for arrow key presses and update the position of the object in the Update function. First, we declare a public float variable speed to represent the speed of the movement. Then, in the Update function, we check for arrow key presses using the Input.GetKey method, passing in the KeyCode enumeration for each arrow key. If the right arrow key is pressed, we add the product of speed and Time.deltaTime to the x position of the object. If the left arrow key is pressed, we subtract the product of speed and Time.deltaTime from the x position of the object. The same process is repeated for the up and down arrow keys, but for the y position of the object.

Here are a few ways you can enhance or optimize the script for moving an object with keyboard input without using a Rigidbody2D component:

--

--

James West

Turning my passion for video games and 11 years of software development experience into a focus on video game development using Unity3D.