x


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.

more ▼

asked Nov 06 '11 at 11:33 PM

Krash gravatar image

Krash
1 1 1 1

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.

Nov 06 '11 at 11:45 PM syclamoth
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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.

more ▼

answered Nov 06 '11 at 11:53 PM

save gravatar image

save
9.5k 22 33 71

Thanks for that. works well. =)

Nov 07 '11 at 08:00 AM Krash
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x5404
x1556
x656
x148
x19

asked: Nov 06 '11 at 11:33 PM

Seen: 12130 times

Last Updated: Aug 31 '13 at 01:33 PM