- Home /
Turret Lock On
i want to have my turret keep shooting at a target until it has either left the max distance, or been destroyed. here's my script:
var Look : boolean = false;
var Target : Transform;
var damp : float;
var Projectile : Transform;
var Shell : Transform;
var MuzzleFlash : Transform;
var fireRate : float = 5;
var Speed : int = 2000;
var ShellSpeed : int = 500;
var TurretAudio : AudioClip;
private var nextFire = .5;
function OnTriggerEnter(other : Collider)
{
if(other.gameObject.tag == "Enemy")
{
Look = true;
Target = other.gameObject.transform;
}
}
function Update()
{
if(Look && Target != null)
{
var rotate = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotate, Time.deltaTime * damp);
Shoot();
}
}
function Shoot()
{
if(Time.time > nextFire)
{
nextFire = Time.time + fireRate;
var muzzleflash = Instantiate(MuzzleFlash, transform.Find("Spawn").transform.position, transform.rotation);
var projectile = Instantiate(Projectile, transform.Find("Spawn").transform.position, transform.rotation);
projectile.rigidbody.AddForce(transform.forward * Speed);
var shell = Instantiate(Shell, transform.Find("Spawn_2").transform.position, transform.rotation);
shell.rigidbody.AddForce(transform.right * ShellSpeed);
audio.PlayOneShot(TurretAudio);
}
}
function OnTriggerExit(other: Collider)
{
if(other.gameObject.tag == "Enemy")
{
Look = false;
}
}
NOTE:
i still want the target to be locked on even if another enemy comes into range.
Your comment is a little vague. Could you please elaborate a little more when you have time?
Answer by Myth · Aug 15, 2012 at 04:36 AM
after more closely examining your code, if you put a "if has no target" around the "target = other...." in the OnTriggerEnter function it would prevent any new target replacing the old one.
Assuming I am not missreading the question, of course.
It works halfway. It will target as it enters and ignore the others that do until the current target is destroyed. But even if the target leaves the trigger, it will keep on targeting the current target until it is destroyed.
Your answer
![](https://koobas.hobune.stream/wayback/20220613075702im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
turret shoot if in range 1 Answer
Gimple lock? ... help me please 2 Answers
Locking onto Multiple AI's 1 Answer
Locking Rotation object on Z axis 1 Answer
Turret Range Script 2 Answers