- Home /
How to move an object around with the arrow keys (Javascript)
I'm new to Unity and is wanting to know how I can select an object with the mouse and move it around using the arrow keys. I'm after a javascript script that will do this for me.
Thanks in advance.
Can't you use a Google search for this? There's a lot of information out there. We're not going to write your game for you.
Answer by save · Nov 06, 2011 at 11:53 PM
Here's a very simple script to show you the basics. Put it on each object you want to move. Make sure that each object has a collider so it can catch the OnMouseDown().
static var selectedId : int;
static var speed : int = 5;
function Update () {
if (selectedId==GetInstanceID()) {
if (Input.GetKey (KeyCode.UpArrow)) transform.Translate (Vector3(0,1,0) * Time.deltaTime*speed);
if (Input.GetKey (KeyCode.DownArrow)) transform.Translate (Vector3(0,-1,0) * Time.deltaTime*speed);
if (Input.GetKey (KeyCode.LeftArrow)) transform.Translate (Vector3(-1,0,0) * Time.deltaTime*speed);
if (Input.GetKey (KeyCode.RightArrow)) transform.Translate (Vector3(1,0,0) * Time.deltaTime*speed);
}
}
function OnMouseDown () {
selectedId = GetInstanceID();
}
selectedId
is made static so it will remain as a single variable, that way only one item can match the id. OnMouseDown() is equal to sending a raycast towards the object, therefore it must have a collider otherwise the ray will pass through. Also have a look at the input class to learn about inputs and steering.