Search code examples
c#unity-game-enginedelayinstantiation

Why sometimes Vector3.Distance is not accurate


So I have this code:

 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class CreateTrail : MonoBehaviour {
        Vector3 lastLocation;
        int traveled;
        public GameObject obj;
        Quaternion lastQuaternion;
        bool on;
        // Use this for initialization
        void Start () {
            lastLocation = transform.position;
            lastQuaternion = transform.rotation;
        }

        // Update is called once per frame
        void Update () {
            if (on)
            {
                if (Vector3.Distance(lastLocation, transform.position) > .1)
                {
                    Instantiate(obj, lastLocation, lastQuaternion);
                    lastLocation = transform.position;
                    lastQuaternion = transform.rotation;
                }
            }
            if (Input.GetKeyDown(KeyCode.Space))
            {
                if (on)
                {

                    on = false;
                }
                else
                {
                    lastLocation = transform.position;
                    lastQuaternion = transform.rotation;
                    on = true;
                }
            }
        }
    }

It creates a trail of objects behind the object it is attached to, but often has the object with the script and the object created inside each other. Is there a way to delay or queue up the object instantiation to when the objects are not inside each other, without interrupting the rest of the script? Thanks!


Solution

  • You can try Coroutine, Invoke or InvokeRepeating to create a delay. (Avoid using Timer and Thread as much as you can.)

    Then add a collider as trigger as a bounding box with its OnTriggerExit or OnTriggerExit2D methods implemented in order to find out when another collider is moved outside the bounding box.


    However, there may be another issue:

    Vector3.Distance returns a float, and when compared to a double (.1) one of them should be cast to the type of the other.

    It is the float which will be implicitly converted to double and will have its accuracy changed.

    You can avoid this by comparing two floats

    if (Vector3.Distance(lastLocation, transform.position) > .1f)
    

    You can find out more about implicit castings here