- Home /
My object is translating with speed but does not stop...
I have a object and I am translating it another point with smooth movement, but it does not stop when it reaches the point and keeps moving forward..... How do I make it stop!!!! Here's my code
void Update () {
coin.transform.Translate (xax*speed*Time.deltaTime, yax*speed*Time.deltaTime, 0);
if (coin.tranform.position==new vector3(xax,yax,0))
{
Debug.Log ("STOP!!!");
coin.transform.Translate (0, 0, 0);
}// "This if does not work"
}
Answer by Zodiarc · Oct 07, 2016 at 07:59 AM
That´s because on the next frame the object is moved either way. Setting the translation to 0,0,0 does not mean the object won't move. The first translate is called frame after frame so the if condition may wor, but has no effect at all. For unity (and other game engines) you need to change your thinking. This isn't a script which runs one time and everything is fine. You need to design your code as if it was surrounded by an infinite loop (which it basically is) and each loop run is one frame.
[System.Serializable]
public class Mover : MonoBehaviour
{
public Transform coin
public float xSpeed = 1.0f;
public float ySpeed = 1.0f;
public void Update()
{
if(Vector3.Distance(this.transform.position, coin.transform.position) > 0.01f) {
this.transform.Translate(this.xSpeed * Time.deltaTime, this.ySpeed * Time.deltaTime, 0)
}
}
}
Should do it. Set the coin ant the speed values to the inspector as you wish.