Moving Cube C# and Unity

I wanted to learn to make a cube which could be controlled by arrow keys to move around in Unity. From here I want to learn trigger events and importing different assets to use instead of a cube.

Here I focused on using the transform.Translate(Input.GetAxis(“Horizontal”)*Time.deltaTime, 0f, Input.GetAxis(“Vertical”)*Time.deltaTime);

The C# code in the project panel of Unity was dragged onto the 3D cube object so the code knew what it was referencing.

This code uses translate, which is a type of transform, telling the cube to read the Unity Horizontal X axis and Vertical Z axis in the axes panel in Edit > Project Settings > Input.

This was written in the void Update () { section of code.

I then added a public float moveSpeed; at the beginning of the code. The float is used so decimals can be an option. Also as this is a public variable it will appear in the Unity editor.

Underneath void Start () { I assigned the moveSpeed =5f, so the speed is of 5 float. This number can be adjusted in the Unity editor during play mode to find the desired speed.

I then returned to my transform.Translate code and added the moveSpeed as a multiplier to the Input.GetAxis for both Horizontal and Vertical.

Voila!

Advertisements

Leave a Reply

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