A while back, someone asked a question on the UnityAnswers site about how to write a script that moves an object in the X/Y direction based on input from the arrow keys.
I wrote a simple script in answer to the question, and I think it makes a nice little example for someone who is new to Unity3D and wondering how to move objects around. It isn’t game-ready (for example, it will plow right through walls and other static scenery), but its simplicity makes it relatively easy to understand and a good starting point for further learning and experimentation.
There are numerous ways to move objects around in Unity3D. You can apply forces to them, explicitly change their position, or use premade scripts such as CharacterController or FirstPersonController.
This example uses what is known as a “kinematic rigidbody” (i.e. an object that interacts with other objects physics-wise but whose motion isn’t controlled by the physics engine), which is moved by calling rigidbody.MovePosition to explicitly change its location.
Click here to see the code in action.
Here’s the Unity3D project for the above example. And here’s the source code for the XYController script, which is attached to the capsule.
XYController.js
#pragma strict // The speed of the keyboard controls. A higher value will // cause the object to move more rapidly. var keyboardSpeed = 20.0; // FixedUpdate is a built-in unity function that is called every fixed framerate frame. // According to the docs, FixedUpdate should be used instead of Update when dealing with a // Rigidbody. // See http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.FixedUpdate.html // for more information. function FixedUpdate () { // This is where we move the object. // Get input from the keyboard, with automatic smoothing (GetAxis instead of GetAxisRaw). // We always want the movement to be framerate independent, so we multiply by Time.deltaTime. var keyboardX = Input.GetAxis("Horizontal") * keyboardSpeed * Time.deltaTime; var keyboardY = Input.GetAxis("Vertical") * keyboardSpeed * Time.deltaTime; // Calculate the new position based on the above input. // If you want to limit the movement, you can use Mathf.Clamp // to limit the allowed range of newPos.x or newPos.y. var newPos = rigidbody.position + Vector3(keyboardX, keyboardY, 0.0); // Move the object. rigidbody.MovePosition(newPos); } // Require a Rigidbody component to be attached to the same GameObject. @script RequireComponent(Rigidbody)
