I have made my own turret using C#, It works as it rotates towards the closest target who is in range and shoots them. my problem is; the child object which spawns the bullet does not rotate with the turret and therefore is always shooting in one direction.
Here is my Turret code:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Targeting : MonoBehaviour {
public List<Transform> targets;
public Transform selectedTarget;
public Transform myTransform;
public Transform objBullet;
public float attackTimer;
public float coolDown;
void Start(){
targets = new List<Transform>();
AddAllEnemies();
selectedTarget = null;
myTransform = transform;
attackTimer = 0;
coolDown = 0.1f;
}
public void AddAllEnemies(){
targets.Clear(); //this is here as enemies spawn and it needs to be reset each time
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in go)
AddTarget(enemy.transform);
}
public void AddTarget(Transform enemy){
targets.Add(enemy);
}
public void SortTargetsByDistance(){
targets.Sort(delegate(Transform t1, Transform t2){
return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
});
}
void Update(){
AddAllEnemies();
TargetEnemy();
transform.rotation = Quaternion.LookRotation(selectedTarget.transform.position-transform.position);
if(attackTimer > 0f)
attackTimer -= Time.deltaTime;
if(attackTimer < 0f)
attackTimer = 0f;
if(attackTimer == 0f){ //this is where the turret shoots
if ( Vector3.Distance(selectedTarget.transform.position,transform.position) < 10f ){
GameObject objCreatedBullet = (GameObject) Instantiate(objBullet, transform.Find("TurretBulletSpawn").transform.position, Quaternion.identity);
Physics.IgnoreCollision(objCreatedBullet.collider, collider);
objCreatedBullet.rigidbody.AddForce(transform.forward * 200);
attackTimer = coolDown;
}
}
}
public void TargetEnemy(){
SortTargetsByDistance();
selectedTarget = targets[0];
}
}
First of all I wouldn't use transform.Find() every time you fire a bullet, much better to just save a variable for bullet spawn, put the Find() in the start function and then save the result.
The second problem is the rotation argument, you've set it to Quaternion.identity, obviously this means that the bullet will always appear facing the same direction (0,0,0)
What you need to do is use your turret's rotation in that bit e.g.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Turret : MonoBehaviour {
public List targets;
public Transform selectedTarget;
public Transform myTransform;
public Transform objBullet;
public float attackTimer;
public float coolDown = 5;
public Transform bulletSpawn;
public void AddAllEnemies(){
targets.Clear(); //this is here as enemies spawn and it needs to be reset each time
GameObject go = GameObject.FindGameObjectsWithTag(“enemy”);
foreach(GameObject enemy in go)
AddTarget(enemy.transform);