A basic homing missile will operate based on three properties: Speed, Auto Destruct time & target.
Important: The following code should be attached to a gameobject having a Rigidbody component with isKinematic set to true.- Speed: Since we are using a kinematic rigidbody, the speed of the projectile can be controlled by translating in the Update() function:
transform.Translate(0,0,speed * Time.deltaTime,Space.Self);
- Auto Destruct: This functionality can be implemented by calling a coroutine which self-destructs after a set amount of time:
function Start () { StartCoroutine(AutoExplode()); } private function ExplodeSelf() { Instantiate(explosion,transform.position,Quaternion.identity); Destroy(gameObject); } private function AutoExplode() { yield WaitForSeconds(autoDestroyAfter); ExplodeSelf(); }
- Target: The missile needs to follow the target. We can achieve this by rotating the missile towards the target transform using the wonderful Slerp function:
var relativePos : Vector3 = target.position - transform.position; var rotation : Quaternion = Quaternion.LookRotation(relativePos); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, homingSensitivity);
#pragma strict
var target : Transform;
var speed : float;
var autoDestroyAfter : float;
//prefab for explosion
var explosion : GameObject;
/* Represents the homing sensitivity of the missile.
Range [0.0,1.0] where 0 will disable homing and 1 will make it follow the target like crazy.
This param is fed into the Slerp (defines the interpolation point to pick) */
var homingSensitivity : float = 0.1;
function Start () {
StartCoroutine(AutoExplode());
}
function Update () {
if(target != null) {
var relativePos : Vector3 = target.position - transform.position;
var rotation : Quaternion = Quaternion.LookRotation(relativePos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, homingSensitivity);
}
transform.Translate(0,0,speed * Time.deltaTime,Space.Self);
}
function OnTriggerEnter(other: Collider) {
//Damage the other gameobject & then destroy self
ExplodeSelf();
}
private function ExplodeSelf() {
Instantiate(explosion,transform.position,Quaternion.identity);
Destroy(gameObject);
}
private function AutoExplode() {
yield WaitForSeconds(autoDestroyAfter);
ExplodeSelf();
}