- Home /
Vector3.MoveTowards doesnt work
i am trying to understand about
Vector3.MoveTowards();
so Vector3.MoveTowards(initial point, destination point, time) when i store the position of the object inside positionOne Vector3 datatype and call Vector3.MoveTowards(positionOne,nextposition,Time.deltaTime*speed);
it doesnt work but when i do
`Vector3.MoveTowards(plankTranform.localPosition,nextposition,Time.deltaTime*speed);`
it works. I dnt understand why. Is first parameter supposed to be initial point or active position of object. I have searched it on official unity manual but unable to find my answer... following is the full code
public class BrickMoveVErtical : MonoBehaviour {
public Vector3 positionOne;
public Vector3 positiontwo;
public Vector3 nextposition;
public Transform plankTranform;
public Transform positionBTransform;
public float speed;
// Use this for initialization
void Start () {
positionOne = plankTranform.localPosition;
positiontwo = positionBTransform.localPosition;
nextposition = positiontwo;
}
// Update is called once per frame
void Update () {
move();
}
private void move() {
plankTranform.localPosition = Vector3.MoveTowards(positionOne,nextposition,Time.deltaTime*speed);
if(Vector3.Distance(plankTranform.localPosition,nextposition)<0.1)
{ changeMovementPlank(); }
}
void changeMovementPlank() {
nextposition = nextposition != positionOne ? positionOne : positiontwo;
}
}
can anyone explain why
plankTranform.localPosition = Vector3.MoveTowards(positionOne,nextposition,Time.deltaTime*speed);
doesn't work.
Answer by Scribe · Jun 02, 2018 at 06:01 PM
Take the difference between the first and second frame where move()
runs :
positionOne
doesn't changenextPosition
doesn't changeTime.deltaTime
might change a tiny amount, but let's assume we have a perfectly consistent value of 0.02f since it's not far off the truthspeed
doesn't change
Since none of the input parameters have changed the output of Vector3.MoveTowards(positionOne,nextposition,Time.deltaTime*speed);
also doesn't change. It will find a value a distance of Time.deltaTime*speed
from positionOne
on the way to nextPosition
and since nothing changed in frame 3, it will find the same value over and over again.
On the other hand when you use plankTranform.localPosition
as the first argument, it does change each frame, as each frame you set it to the slightly different position calculated from Vector3.MoveTowards(plankTranform.localPosition,nextposition,Time.deltaTime*speed);
so it progresses towards nextPosition.
Hope that helps,
Scribe