Moving GameObject a specific distance in the Z direction and back again - regardless of rotation
Hello -
I am a beginner and working on my first 3D game.
I need to be able to programmatically move a GameObject in its forward direction a certain distance, determine when it reaches that distance, and then return it back to its starting point.
I can make this work using Vector3.MoveTowards and Transform.Forward - the problem I face is that the GameObject could be at a different rotation everytime the game is played as it is dynamically created in the environment based on where a user taps.
So I need to move forward the direction it is facing at runtime and back again regardless of rotation.
I am using C#
I appreciate any help!
Answer by ClearRoseOfWar · Jul 14, 2016 at 05:17 AM
Your looking for transform.translate(Vector3.Forward,space.World);
https://docs.unity3d.com/ScriptReference/Transform.Translate.html
DLively - Thank you for the help! It seems I can get my object to move in the correct right direction every time using this logic. However, the problem I face is deter$$anonymous$$ing when I have traveled the preset distance of 1f in Z. Here's the code I am using now to move it and deter$$anonymous$$e if I've reached the distance I need to. It doesn't seem to work correctly as sometimes it will overshoot the distance or sometimes not go far enough depending on the rotation in Y of the game object. Am I calculating the distance traveled wrong once it starts moving?
 startingPoint = new Vector3(transform.position.x, transform.position.y, transform.position.z);
 zDistance = 1f;
 comeback = false
 
 void Update ()
 {
 if(!comeback)
 {
 Debug.Log("I'm moving forward");
 lastPos = transform.position;
 distance = lastPos - startingPoint;
 zDistanceTraveled = $$anonymous$$athf.Abs(distance.z);
 Debug.Log("Total Distance I $$anonymous$$ust Go:" + zDistance);
 Debug.Log("Distance I've Traveled:" + zDistanceTraveled);
                 
  if (zDistanceTraveled >= zDistance)
 {
 comeback = true;
 }
 else
 transform.position += transform.forward * Time.deltaTime * speed;
 }
 }
 
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                