Moving an object in Unity5

Hi ! Today I want to show you how to move the GameObject in unity5 !

Moving the object around sounds like a simple task ,Yes it sure is in unity ! So let’s check it out !

 

So lets start writing the code in a sample .cs file.

 

[Precondition]

Set couple of necessary variables that you will need

Vector3 moveDirection = Vector3.zero;

public float gravity;

public float speedZ;

public float speedJump;

 

  1. [Obtain the Components]

As a default there should be a Start method, in there we will set the following code to get the components from the CharacterController and the Animator.

controller = GetComponent<CharacterController>();

animator = GetComponent<Animator>();

2. [Set the Movements]

Now we will start writing inside the Update method.

First lets check if the CharacterController object is on the ground. If so let’s have the object controllable!

if (controller.isGrounded)

Lets add the code to detect the user inputs.

if (Input.GetAxis("Vertical") > 0.0f) {

moveDirection.z = Input.GetAxis("Vertical") * speedZ;

} else {

moveDirection.z = 0;

}

This code will be for rotating the direction

transform.Rotate(0, Input.getAxis("Horizontal") * 3, 0);

Here is the cool part ! Jumping !  The setTrigger method will make the

Animator object animate . For more information It will be best to check out about Mecanim in Unity5.

if (InputGetButton("Jump")) {

moveDirection.y = speedJump;

animator.setTrigger("jump");

}

Will add the gravity so that the object may come back down after jumping, because you don’t want it to be flying upwards each time !

moveDirection.y  -=  gravity * Time.deltaTime;

Here comes the code for moving the object . We will be setting the moveDirection, so that the local Vector variable may be set globally.

I’ve added the Time.deltaTime to prevent the difference in frameRate..It’s hard to explain this part.

Vector3 globalDirection = transform.Transform.TransformDirection(moveDirection);

controller.Move(globalDirection * Time.deltaTime);

Ok the movement is set, and finally lets set the movements y value to default after landing.

if (controller.isGrounded) moveDirection.y = 0

If you have a animation state for running why don’t you add the following code so that the object may look like running ?  But only if the

moveDirection.z is greater is 0.

animator.SetBool("run", moveDirection.z > 0.0f);

Over ? Yes it’s over. It was simple isn’t it ?

Leave a Reply

Your email address will not be published. Required fields are marked *