- Home /
How to make a bullet explode on impact
I am making a tank game in which I would like the bullet to be fired and explode on impact with an enemy AI tank. The script I am currently using for the bullet is:
var colision = 0; var bulletspeed = 400; var bullet : Transform; function Update () { if(Collision){ if(colision == 3){ } else{ colision +=1; rigidbody.velocity = transform.TransformDirection(Vector3(0,0,bulletspeed)); } } else{ rigidbody.velocity = transform.TransformDirection(Vector3(0,0,bulletspeed)); } }
I have also assigned the bullet prefab this script to make it explode on impact with the enemy tank:
var explosion : ParticleEmitter;
function OnCollisionEnter (col : Collision) {
Instantiate(explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
But the bullet seems to be exploding as soon as it leaves the muzzle of the tank's barell. I think this is because the bullet is touching the tank that has just fired it, but I can't find any part of the script to adjust to make it appear just in front of the barell so that it can continue on its trajectory and hit the enemy tank.
Cheers
Answer by perchik · Feb 15, 2012 at 08:47 PM
The bullet is probably colliding with the barrel. You can check the name of the collider before instantiating something, so like
var explosion : ParticleEmitter;
function OnCollisionEnter (col : Collision) {
if(col.name !="Tank"){
Instantiate(explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
}
I tried this but this cameup
UnassignedReferenceException: The variable explosion of 'exsplod' has not been assigned. You probably need to assign the explosion variable of the exsplod script in the inspector. UnityEngine.Object.Internal_InstantiateSingle (UnityEngine.Object data, Vector3 pos, Quaternion rot) (at C:/BuildAgent/work/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:44) UnityEngine.Object.Instantiate (UnityEngine.Object original, Vector3 position, Quaternion rotation) (at C:/BuildAgent/work/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineObject.cs:53) exsplod.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Standard Assets ($$anonymous$$obile)/Scripts/exsplod.js:4)
Answer by TEBindustries · Feb 16, 2012 at 01:39 PM
Thanks, but it hasn't solved the problem. I have many variations such as:
var explosion : ParticleEmitter;
function OnCollisionEnter (col : Collision) {
if(col.name !="Tank") Instansiate = false;
if(col.name !="EnemyTank") Instansiate = true;
Instantiate(explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
but it still explodes as soon as it is fired.
I'm sorry, i thought you understood program$$anonymous$$g and didnt type out the full code. i've updated my answer