Auto aim and shoot turret issues

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?

OK, found my problem. for some reason this doesn’t work well:

targetPos = Quaternion.LookRotation (target.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetPos, Time.deltaTime * 5);

but if i replace it back with Transform.lookat(target) it works fine.
not exactly as i want but much better.

thanks for sharing it i found it so amazing Youtube Go glad to be here

Thanks, it works for me too. but I also have to replace transform.lookat. iMegaCam for Pc. However, thanks again.

I’m glad somebody’s still talking about these subjects. Even I’m unable to discuss such issues on my technology blog @WikiesforPC

hard to understand such topics but good work keep it up.
Reviews About New Apps And Games Click Here