- Home /
Missle Distry after it reaches distance
I have the following codes making my missles launch from my aircraft and it all works. My problem lies in the fact that when the bullets fire and if it dont hit anything it never disapears. I would like it to self destroy after it reaches a decent amout of distance from the ship.
This is the missle launcher:
var missile : GameObject;
function Update () {
if (Input.GetMouseButtonDown (0))
{
var position : Vector3 = new Vector3(0.004, -.001, 0) * 10.0;
position = transform.TransformPoint (position);
var thisMissile : GameObject = Instantiate (missile, position, transform.rotation) as GameObject;
Physics.IgnoreCollision(thisMissile.collider, collider);
}
}
This is for theTrajectory:
var explosion : GameObject;
function FixedUpdate () {
rigidbody.AddForce (transform.TransformDirection (Vector3.forward) * 200.0);
}
function OnCollisionEnter(collision : Collision) {
var contact : ContactPoint = collision.contacts[0];
var thisExplosion : GameObject = Instantiate (explosion, contact.point + (contact.normal * 5.0) , Quaternion.identity);
if (collision.gameObject.tag == "enemy")
{
Destroy (collision.gameObject);
}
Destroy (thisExplosion, 2.0);
Destroy (gameObject);
}
Answer by AlucardJay · Oct 05, 2012 at 09:13 PM
The easiest way is to give the missile a life-span as soon as it is Instantiated
function Start()
{
Destroy( gameObject, 4.0 );
}
then 4 seconds after it appears , Destroy (or give it long enough to fly far enough into the distance).
the method you're asking for is to check the distance. For this you can use Vector3.Distance : http://docs.unity3d.com/Documentation/ScriptReference/Vector3.Distance.html
function Start()
{
InvokeRepeating( "CheckDistance", 0.5, 0.2 );
}
function CheckDistance()
{
if ( Vector3.Distance( player.transform.position, transform.position ) > 20.0 )
{
Destroy( gameObject );
}
}
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.InvokeRepeating.html
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Spawning portal 1 Answer
Convert JS to C# 1 Answer
problem sending information from js script to c# script 1 Answer
Making a Jetpack 3 Answers