I got a rocket that follow you until it collide with something and explode.
I wrote a simple code for the collision. The problem is that the rocket don’t explode when it should: it fly through walls , touch me but continue to fly around, it explode only when I shoot on it.
The code I wrote shoulde make it explode when it collide with anything that have a collider, trigger or not:
var explodPrefab : Transform;
var spawnPoint : Transform;
function OnCollisionEnter (hit : Collision)
{
var exp = Instantiate(explodPrefab, spawnPoint.transform.position, Quaternion.identity);
Destroy(gameObject);
}
function OnTriggerEnter (hit : Collider)
{
var exp = Instantiate(explodPrefab, spawnPoint.transform.position, Quaternion.identity);
Destroy(gameObject);
}
Note: all the game objects have a collider on them.
Based on your description, I don’t think your collision detection is working correctly. Do both your rocket and the object it is colliding with have colliders on them? Both will need a collider for a collision to be detected.
I read somewhere that for fast moving objects the collider will pass through objects without triggering a collision (ie gets past object between ‘updates’). Try making the collider bigger or slowing down the rocket.
Try the script from the first person shooter tutorial. Script also assumes you have a particle emitter attached for the rocket trail.
I use this and it works perfectly.
// The reference to the explosion prefab
var explosion : GameObject;
var timeOut = 3.0;
// Kill the rocket after a while automatically
function Start () {
Invoke("Kill", timeOut);
}
function OnCollisionEnter (collision : Collision) {
// Instantiate explosion at the impact point and rotate the explosion
// so that the y-axis faces along the surface normal
var contact : ContactPoint = collision.contacts[0];
var rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
Instantiate (explosion, contact.point, rotation);
// And kill our selves
Kill ();
}
function Kill () {
// Stop emitting particles in any children
var emitter : ParticleEmitter= GetComponentInChildren(ParticleEmitter);
if (emitter)
emitter.emit = false;
// Detach children - We do this to detach the trail rendererer which should be set up to auto destruct
transform.DetachChildren();
// Destroy the projectile
Destroy(gameObject);
}
//@script RequireComponent (Rigidbody)