Problems with collision detection

I’m developing a long range shooting simulator. My bullet have a sphere collider that I used to detect collision on the method OnCollisionEnter. But as I increase the bullet speed, sometimes Unity does not detect the collision correctly. Sometimes it happen that I shoot many times without moving the mouse, and the collision is only detected in some of the shots. The bullet have a rigibody to suffer the effect of gravity.

My script of the bullet moviment:

void Update()
    {
        transform.Translate(Vector3.forward * speed * Time.deltaTime);
        Destroy(this.gameObject, timeToLive);
    }

May have no relation to the movement of the bullet. I noticed that some times the bullet is destroyed before the scheduled time. And it happens with or without method Destroy.

Does anyone know what could be the problem?

Hi @lkrueger

If you are making the object move and it has a Rigidbody component that isn’t kinematic. Then it is always the best practice to make sure that you are moving the object by it’s Rigidbody values such as velocity etc. Usually within the FixedUpdate () method. This ensures that the collider is kept in check throughout the physics calculations. If you’re moving the object by it’s Transform when it is supposed to be effected by gravity etc. You’ll will run into lot’s of little problems as you’re calculating the movement of the object whilst the object is separately calculating the physics of the collider and Rigidbody component.

Also, another little point, there is no need to call Destroy() in the Update method. This method will be called after the time passed in has elapsed, so you can call it within the Awake () or Start () methods and it will still function exactly the same. Calling it within update create’s a tiny but, unnecessary overhead on the game.

A quick revision of what you could do to your code is as follows:

private Rigidbody _Rigidbody = null;

void Awake ()
{
      Destroy(this.gameObject, timeToLive);
      _Rigidbody = GetComponent<Rigidbody> ();
}

void FixedUpdate()
{
      _Rigidbody.velocity = Vector3.forward * speed;
}

Please note, I haven’t tested the code above, but it should work. I hope this helps.