0
\$\begingroup\$

Why does the following code not step the object's movement when its y coordinate reaches zero?

    public GameObject cube;
    private GameObject inst;
    public float speed=5;


    void Start () {
        inst = Instantiate(cube, new Vector3(0, 10.6f, 0),Quaternion.identity);
    }


    void Update () {

        inst.transform.Translate(speed * Vector3.down * Time.deltaTime, Space.World);

        if (inst.transform.position.y == 0)
        {
            speed = 0; //stop moving
        }
    }
\$\endgroup\$
5
\$\begingroup\$

Because the Y position is never EXACTLY 0.

Its for example 5.5 next frame: 4.3 next frame: 3.1 next frame: 1.9 next frame: 0.7 next frame: -0.5

change the if to

if (inst.transform.position.y <= 0)

Then add:

inst.transform.position = new Vector3(inst.transform.position.x, 0, inst.transform.position.z);

next to:

speed = 0;
\$\endgroup\$

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.