Moving Objects Through Scripting in Unity3D

You can make objects move in Unity3D without animating them. Use JavaScript! Or C#, but for right now I’m going to show you how to do it with JavaScript. That’s what most Unity developers use.

So, first create a new JavaScript and open it up. Type this in it: (don’t copy and paste, you won’t learn)

function Update () {
transform.Rotate (1,0,0);
}

Save that, and attach it to a GameObject. Play the game, and you will see that whatever object you have attached the script to will be rotating in the x axis. The speed of this rotation is dependent upon the frame per second of your game. So if you have a really fast computer, the object will probably be spinning quite fast.

A few tips:

Transform means location or position.
transform.Rotate means rotate the position.
That (1,0,0) means rotate in the x axis; not y, not z.
Don’t forget the semi colon at the end of line 2.

So how about we make the object rotate at a fixed speed? That’s easy enough. Type this up:

var rotateSpeed: int=4;

function Update () {
transform.Rotate(Vector3.right*Time.deltaTime*rotateSpeed);
}

A few tips:

var means variable
int means integer
Time.deltaTime means, basically, time.
Multiply that by our variable, rotateSpeed (use the asterisk)

Make sure you save and update the script and all that and that, and you’re ready to go! If you want to change the axis of rotation, change Vector3.right to Vector3.up or Vector3.left or whatever.

Done!

Advertisements

What Are Your Thoughts?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s