All,
Below is a script that i found online. The idea is for a turret to follow the player by (looking at him). It worked fine after finessing it a bit. I realized that I had to ensure that the object that the “follow” script was attached to was on the same y axis as the player.
For some reason, after I rebuilt my player prefab, (My previous one was corrupted) The object will not follow the player. I tried to ensure that the Transform Y value was the same for my player’s ship and the turret object. I am not sure what if the issue is code related, or if I’ve done something wrong in the prefabs. Any suggestions would be greatly appreciated.
PS: I’m making a top down shooter.
var attackRange = 30.0;
var shootAngleDistance = 10.0;
var FireFreq : float ;
var enemyBullet : GameObject;
var enemyBullet2: GameObject;
private var lastShot : float;
var target : Transform;
function Start () {
if (target == null GameObject.FindWithTag("Player"))
target = GameObject.FindWithTag("Player").transform;
}
function Update () {
if (Time.time > lastShot + FireFreq){
Shoot();
}
if (target == null)
return;
if (!CanSeeTarget ())
return;
// Rotate towards target
var targetPoint = target.position;
//targetPoint.y = transform.position.y;
var targetRotation = Quaternion.LookRotation (targetPoint - transform.position, Vector3.up);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0);
// If we are almost rotated towards target - fire one clip of ammo
var forward = transform.TransformDirection(Vector3.forward);
var targetDir = target.position - transform.position;
if (Vector3.Angle(forward, targetDir) < shootAngleDistance){
}
}
function Shoot() {
lastShot = Time.time;
// bulletposition2 = gameObject.transform.TransformPoint(Vector3.back * -3);
Instantiate ( enemyBullet, transform.position, Quaternion.Euler (Vector3(0, -90,0) ));
Instantiate ( enemyBullet2, transform.position, Quaternion.Euler (Vector3(0, 90,0) ));
}
function CanSeeTarget () : boolean
{
if (Vector3.Distance(transform.position, target.position) > attackRange)
return false;
var hit : RaycastHit;
if (Physics.Linecast (transform.position, target.position, hit))
return hit.transform == target;
return false;
}