am trying to do a homing missile effect in my work. need to know if there is any tutorials or intro to how to start with. need help.
You can use my code, for a 2d game, although it should work for a 3d game as well I think:
using UnityEngine;
using System.Collections;
public interface Damagable {
int GetOwner();
void TakeDamage(float damage);
}
public class Missile : MonoBehavoiur {
private Transform target;
private int owner;
private float damage;
protected float range;
protected float rotationRate;
public void CreateObject(Vector3 start, Transform target, Vector3 facing, int owner, float damage, float range, float speed, float rotationRate) {
Missile missile = (Missile)Instantiate(this, start, Quaternion.identity);
missile.owner = owner;
missile.damage = damage;
missile.range = range;
missile.rotationRate = rotationRate;
missile.rigidbody.velocity = facing.normalized * speed;
missile.target = target;
}
public void FixedUpdate() {
range -= rigidbody.velocity.magnitude * Time.fixedDeltaTime;
if (range <= 0) {
GameObject.Destroy(gameObject);
}
if (target == null)
return;
Vector3 toTarget = target.position - transform.position;
Vector3 newVelocity = Vector3.RotateTowards(rigidbody.velocity, toTarget, rotationRate * Mathf.Deg2Rad * Time.fixedDeltaTime, 0);
newVelocity.z = 0;
rigidbody.velocity = newVelocity;
}
public void OnTriggerEnter(Collider other) {
MonoBehaviour[] monos = other.GetComponents<MonoBehaviour>();
foreach (MonoBehaviour mono in monos) {
if (typeof(Damagable).IsAssignableFrom(mono.GetType())) {
Damagable damaged = (Damagable)mono;
if (damaged.GetOwner() >= 0 && damaged.GetOwner() != owner) {
damaged.TakeDamage(damage);
GameObject.Destroy(this.gameObject);
}
}
}
}
}
Now, every object that you want the missile to be able to hit must implement the Damagable
interface, and must have a different owner than the missile (that way missiles don’t hit friendly targets). You can remove the owner check if you want friendly fire to be possible.
To launch the missile, create a missile prefab, attach this script, and when you want to launch it, call the CreateObject()
method of the prefab.
Note that this was written for a torpedo style missile, so it’s more like a ball of energy. That’s why the mesh doesn’t rotate. If you have a missile that has a head and tail, you’ll want to rotate it in the FixedUpdate() to face the direction of the velocity:
transform.forward = rigidbody.velocity.normalized;