OnCollisionEnter is slow...

Hello!

I have this script attached to my bullet object that is supposed to destroy it when touching a Collider, and Instantiate a particle.

The problem is that the bullet goes so fast, that the particle Instantiate not exactly the same time when the bullet collides, but a bit later, after the bullet has changed its direction from the hit, because the OnCollisionEnter function doesn’t destroy the bullet on time…

#pragma strict
var DirtHit : GameObject;

function Start () {
rigidbody.AddRelativeForce (Vector3.forward * 1000);
yield WaitForSeconds(3);
Destroy(gameObject);
}

function OnCollisionEnter (other : Collision) {
Destroy(gameObject);
Instantiate(DirtHit, transform.position, transform.rotation);
}

It has a cube collider, if this helps…

2 Answers

2

Let’s say your game runs at 60 frames per second.
If we assume that the deltaTime between each frame stays stable (best case scenario) then the bullet travels 1/60 * 1000 = 16.666 units between each frame.

I would therefore use a Raycast each tick, forward more than 16.666 units. Try 20 and see what happens.

When you detect a RaycastHit, you could use the position of that hit for the DirtHit instant.

Thanks! But how I will insert the raycast on my script? It will be on the bullet or the gun?

Raycast from the bullet. If you search youtube for "Unity Bullet Holes" you should get a few good tutorials, even though you're not doing bullet holes the principle is very similar.

In the inspector have you tried altering the collision detected to either Continuous or Continuous Dynamic from Discrete?

Yes, it has the same result