Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How can the gameobjects in unity be moved back and forth linearly

    • 0
    • 5
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.84k
    Comment on it

    If you want to move gameobjects back and forth in unity than you can do this by using a function  Mathf.PingPong. This function takes two float
    values we can say 'q' and 'length'. It will ping-pong the value 'q' so that it can never be larger than 'length' and never smaller than zero.

    To do this create a 3D gameobject by going to Menu>Gameobject>3D Object>Cube and place it at position(0,0,0). After this create a C# script and name it as CubeMovement and attach it to the gameobject you created.

    Add the following code to the script:

    using UnityEngine;
    using System.Collections;
     
    public class CubeMovement  : MonoBehaviour
    {
      public float speed = 2;
      void Update()
    {
      transform.position = new Vector3(Mathf.PingPong(Time.time*speed, 4), transform.position.y, transform.position.z);
    }
     
    }


    This will move the cube from (0, 0, 0) to (4, 0, 0) and back to (0, 0, 0) and so on. You can apply this to other axis as well.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: