Hi,
i found JS of automatic aim and shoot turret and convert it to C#.
this is what i got(with some improvement of mine to smooth the movement):
using UnityEngine;
using System.Collections;
public class TurretController : MonoBehaviour {
public Rigidbody bulletPrefab;
private Transform target;
private GameObject bullet;
private float nextFire;
private Quaternion targetPos;
void OnTriggerEnter(Collider otherCollider) {
if (otherCollider.CompareTag("airplane"))
{
Debug.Log ("in");
target = otherCollider.transform;
StartCoroutine ("Fire");
}
}
void OnTriggerExit(Collider otherCollider) {
if (otherCollider.CompareTag("airplane"))
{
Debug.Log ("out");
target = null;
StopCoroutine("Fire"); // aborts the currently running Fire() coroutine
}
}
IEnumerator Fire()
{
while (target != null)
{
nextFire = Time.time + 0.5f;
while (Time.time < nextFire)
{
// smooth the moving of the turret
targetPos = Quaternion.LookRotation (target.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetPos, Time.deltaTime * 5);
yield return new WaitForEndOfFrame();
}
// fire!
Debug.Log ("shoot");
bullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as GameObject;
//bullet.rigidbody.velocity = transform.forward * bulletSpeed;
}
}
}
it’s work fine when i place single turret on the screen. when the plane enter the collision area it trigger the aiming and get shot.
problems starts when i instantiate several turrets in my scene. (they placed in line along Z axis) then they all act weird. basically they all move together get stuck on some point and shot there. the first and second turrets in line kind of work OK.
i thought it because they “trigger” each other so i placed them in another layer changed layers collision settings so object in the same layer will not collide with them self.
(but since i use trigger i’m not sure it effective ).
so, any advice what could be wrong or how can i implement a better turret?