- Home /
Homing missile not working.
Hi. Im trying to make a 2d spaceship game. Im making a homing missile, but when I fire it, it won't follow the enemies.
My enemies have tag "nem", and here's my missile code: #pragma strict
var target : Transform;
function Start () {
}
function Update () {
if(target){
Debug.Log("A");
transform.LookAt(target);
}
transform.Translate(Vector3.up * Time.deltaTime * 10);
}
function OnCollisionEnter(other : Collision){
if(other.gameObject.tag == ("nem")){
target = other.gameObject.transform;
Debug.Log("B");
}
}
//
//function OnCollisionEnter
If I use the on collision enter however, the missile goes crazy so I don't want to use it. What's the difference anyway? colliding or being inside object's trigger zone I guess. Oh and it won't show either A -debug.log nor B. Should be easy for you.
Answer by aldonaletto · Jun 08, 2013 at 11:22 PM
How do you expect to chase the enemy if the target variable isn't being set? Setting it in OnCollisionEnter is useless, since this event will only occur when the missile hits the enemy! A possible solution is to do a raycast when the missile is fired, and if an enemy is hit set target to its transform - like this:
var missileSpeed: float = 10;
var target: Transform;
function Start(){
// move the missile at missileSpeed velocity:
rigidbody.velocity = transform.forward * missileSpeed;
// check if an enemy is in the line of fire:
var hit: RaycastHit;
if (Physics.Raycast(transform.position, transform.forward, hit)){
if (hit.gameObject.CompareTag("nem")){
target = hit.transform; // if so, lock the missile on it
}
}
}
function Update(){
if (target){ // if target locked, set velocity in its direction
transform.LookAt(target);
rigidbody.velocity = transform.forward * missileSpeed;
}
}
I forgot to tell that I made the sphere collider a huge so it kind of collides with it all the time, but.. I'll test this now.
Okay now it works.. somehow. I just need to figure out how to lock more than one missile to one target. Thanks for your time.