- Home /
Homing missle with raycast
hi i have been learning scripting and decide to try to make a lock on missile so Ive been looking and all the tutorials have a script that just look for the closest obj with the tag enemy and etc but what i want is a way to make the missile lock on to a target using a raycast from the middle of the screen hears the code ive been learning from `
#pragma strict
var _velocity : float = 10;
var _torque: float = 5;
var _target : Transform;
var _rigidbody : Rigidbody;
function Start()
{
_rigidbody = transform.rigidbody;
Fire();
}
function Fire()
{
var distance = Mathf.Infinity;
for (var go : GameObject in GameObject.FindGameObjectsWithTag("Enemy")) {
var diff = (go.transform.position - transform.position).sqrMagnitude;
if(diff < distance)
{
distance = diff;
_target = go.transform;
}
}
}
function FixedUpdate()
{
if(_target == null || _rigidbody == null)
return;
_rigidbody.velocity = transform.forward * _velocity;
var targetRotation = Quaternion.LookRotation(_target.position - transform.position);
_rigidbody.MoveRotation(Quaternion.RotateTowards(transform.rotation, targetRotation, _torque));
}
function OnCollisionEnter(collision : Collision)
{
Destroy(gameObject);
}
p.s. i know how to use the raycast function but Im just confused on implementing it into the code.
Have a transform variable and then assign the raycast hit to that variable then have the rocket object move towards your transform variable.
Answer by Firedan1176 · Nov 27, 2014 at 01:00 AM
Why can't you do transform.LookAt? You can make your gun rotate and face an enemy, but also smooth it out if you want. You can do the same for your missile.