Unity - Move Gameobject Back And Forth

This is going to be a very quick post on How to move a Gameobject Back and Forth in a linear way. The Mathf.PingPong function is all that you need to use to get this done. This function takes in two float arguments, say 't' and 'length'. This function Pingpongs the value t so that it is never larger than length and never smaller than 0.

We will use this to Pingpong the transform's position back and forth the desired range.

To get started, create a new empty scene and add a Cube by navigating to 3D Object -> Cube. Position it at (0, 0, 0), if it's not already at that position.
Add a directional light, just to make the scene more bright.

Create a new C# Script named BackForthMovement and attach it to the Cube that you created just now.
Open the script and add the below code to it.

using UnityEngine;
using System.Collections;

public class BackForthMovement : MonoBehaviour {

 public float speed = 1;

 void Update() {
  //move the cube from (0, 0, 0) to (5, 0, 0) and back to (0, 0, 0) and so on.
  //use the same Mathf.PingPong function to the other axes if you need to move in those axes as well
  transform.position = new Vector3(Mathf.PingPong(Time.time*speed, 5), transform.position.y, transform.position.z);
 }

}

Save the script and return to unity and test the scene. You should notice that the cube moves from (0, 0, 0) to (5, 0, 0) and back and forth.

Move Object Back and Forth - Unity
You would also notice that the cube moves 1 unit in 1 second time. That is what the Time.time is used for. If you want to move the Cube at a higher speed, say 3 units a second. Then you would simply change the value of speed to 3.

If you are wondering, is there any way to change the default starting position of Mathf.PingPong from (0, 0, 0) to something else. Well, sadly there is any such predefined function. But fortunately, we are programmers. We can manipulate this function and make it possible.

using UnityEngine;
using System.Collections;

public class BackForthMovement : MonoBehaviour {
 public float speed = 1;
 void Update() {
  //move the cube from (0, 0, 0) to (5, 0, 0) and back to (0, 0, 0) and so on.
  //use the same Mathf.PingPong function to the other axes if you need to move in those axes as well
  transform.position = new Vector3(PingPong(Time.time*speed, -5, 5), transform.position.y, transform.position.z);
 }

 //function to change the default starting value of (0, 0, 0) to any value
 float PingPong(float t, float minLength, float maxLength) {
  return Mathf.PingPong(t, maxLength-minLength) + minLength;
 }
}


Replace the code in the BackForthMovement script with the above code and you should see that the cube now moves from (-5, 0, 0) to (5, 0, 0) and back and forth.

Move Object Back and Forth - Unity
This was a very simple and efficient way of moving an object back and forth. Now what if you want to have an object move in one direction until it hits something and once it does hit that something, it should change the direction and should move in the exact opposite direction just like the way in which the tortoises used to move in the classic Mario Bros. game?

Well, in that case we we need to setup two objects around the cube so that it moves back and forth in the space between them.

Add two more cubes and position them at (-4, 0, 0) and (4, 0, 0) respectively. You can name them as Cube1 and Cube2 or anything for that matter.
The setup would look like

Move GameObject Back and Forth  Mario Bros. style - Unity
Also, add a Rigidbody component to the Cube gameobject so that we can detect when it enters into a trigger with the other two cubes. Uncheck the Use Gravity checkbox so that it doesn't fall off.

Rigidbody Component properties


Tag the two cubes - Cube1 and Cube2 with tag Finish.

Tag Cubes
Check the Is Trigger checkbox of the Box Collider component for these two cubes.

Check Is Trigger property
Once you are done with this, replace the code in the BackForthMovement with the code below:

using UnityEngine;
using System.Collections;

public class BackForthMovement : MonoBehaviour {
        //speed at which the object moves back and forth
 public float speed = 3;
        //direction in which the object moves. 1 is for right and -1 for left
 float dir = 1;
 
 void Update(){
                //move the object at a rate of 1*speed unit/s along the x-axis
  transform.Translate(new Vector3(1, 0, 0) * Time.deltaTime * dir * speed);
 }
        
        //check if the object hits the other two cubes
 void OnTriggerEnter(Collider coll){
                //check if the object enter into a trigger with objects named Finish
  if(coll.gameObject.tag=="Finish"){
                        //reverse the current direction 
   dir *= -1;
  }
 }

}

Save the script and return to unity and test the scene. You should notice that the object would move in one direction until it hits one of the cube and it reverses it's direction once it does so.

Move GameObject Back and Forth  Mario Bros. style - Unity

This is all it in this post. Hope you all liked it.

See you around
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

1 comments: