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
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:
public class MoveObject : MonoBehaviour
public float speed = 5f;
private void Update()
transform.position += new Vector3(speed * Time.deltaTime, 0f, 0f);
transform.position -= new Vector3(speed * Time.deltaTime, 0f, 0f);
transform.position += new Vector3(0f, speed * Time.deltaTime, 0f);
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
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
Time.deltaTime to the
x position of the object. If the left arrow key is pressed, we subtract the product of
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