How to move a object from point A to point B and back again (3D)
I am trying to move a object across the screen and have written a script that can move it from its spawn to the place i want it to go but i can't get it to go back. I know that there is a problem with the script as i used if statements as i did not know a better way of moving it. The object starts at X 12 and should stop at X 2.5 and return to the spawn point however i cant get it back.
using UnityEngine; using System.Collections;
public class Mover : MonoBehaviour { void Update() {
if (transform.position.x < 2.5) {
transform.Translate (Vector3.right * Time.deltaTime);
}
else
{
transform.Translate(Vector3.left * Time.deltaTime);
}
//transform.Translate(Vector3.up * Time.deltaTime, Space.World);
}
} Any and all help is appreciated.
Answer by DCordoba · Jan 23, 2016 at 05:57 PM
first, maybe you seeing it from a rare point of view, this script just will move the object until less than 2.5, but when reaches this position will back again just one frame because next frame the object will be a bit more than 2.5, so will came down to less 2.5 again.
so, the object go well until reaches 2.5, after that just jump between two positions transform.x <2.5
and transform.x >= 2.5
so you need to simulate a state of the object, and change it when reach 2.5
first declare a Enum (or something) out of the current method to simulate the state, and use that state to check if the object have reached yet the point of 2.5
some like
public enum GoingTo
{
Forward, Backward, None
}
public class Mover : MonoBehaviour {
void Update() {
GoingTo State = GoingTo.Forward;
if (transform.position.x < 2.5f) {
//if you have reached the maximium position
//En español, si ya has llegado a la maxima posicion
State = GoingTo.Backward;
}
else
{
//if you are going backward and reached the original position
//si estas regresando y alcanzaste la posicion original
if(State == GoingTo.Backward && 12.0f <= transform.position.x){
State = GoingTo.None;
}
}
//here make movement of each "state"
//aqui se "da movimiento" a cada "estado"
switch(State){
case(GoingTo.Forward):
transform.Translate (Vector3.right * Time.deltaTime);
break;
case(GoingTo.Backward):
transform.Translate(Vector3.left * Time.deltaTime);
break;
default:
//you have rached the original position, what you'll do now?
//has alcanzado la posicion original, ¿ahora que sigue? (borra este print, se ejecuta cada frame y te sobrecargará el procesador)
Debug.Log("Movement Completed, Waiting... Completado el movimiento, Esperando...");
break;
}
}
}