- Home /
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...
Answer by alexanderbrevig · May 03, 2013 at 08:33 AM
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.
Answer by SubatomicHero · May 03, 2013 at 08:22 AM
In the inspector have you tried altering the collision detected to either Continuous or Continuous Dynamic from Discrete?
Your answer
Follow this Question
Related Questions
OnCollisionEnter not being called, between a Rigidbody and a Box Collider 1 Answer
Checking Collision on instantiated object 0 Answers
Instantiated object not colliding when not have a rigidbody?? 2 Answers
How can I instantiate rigid bodies on top of each other without them exploding away? 2 Answers