using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TurretScript : MonoBehaviour {
public float shotInterval = 0.2f; // interval between shots
public Rigidbody bulletPrefab; // drag the bullet prefab here
public int speed=10;
public float shootTime = 0.0f;
public List targets;
public Transform selectedTarget;
public Transform myTransform;
public Transform bulletSpawn;
void Start(){
targets = new List();
selectedTarget = null;
myTransform = transform;
bulletSpawn = transform.Find (“bulletSpawn”); // only works if bulletSpawn is a turret child!
}
void OnTriggerEnter(Collider other){
if (other.tag == “Enemy”){ // only enemies are added to the target list!
targets.Add(other.transform);
}
}
void OnTriggerExit(Collider other){
if (other.tag == “Enemy”){
targets.Remove(other.transform);
}
}
void TargetEnemy(){
if (selectedTarget == null){ // if target destroyed or not selected yet…
if (targets.Count > 0) selectedTarget = targets[0];
}
}
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(){
Debug.Log (“shooting”);
BulletScript script = GetComponent();
TargetEnemy(); // update the selected target and look at it
if (selectedTarget){ // if there’s any target in the range…
transform.LookAt(selectedTarget); // aim at it
if (Time.time >= shootTime){ // if it’s time to shoot…
Rigidbody bullet = (Rigidbody)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.AddForce(transform.forward*speed); // shoot in the target direction
shootTime = Time.time + shotInterval; // set time for next shot
}
}
}
}///////////////////////////////////////////////////////Turret script
using UnityEngine;
using System.Collections;
public class BulletScript : MonoBehaviour {
public GameObject Bullet;
public float speed;
public int Damage;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void Fire()
{
Instantiate(Bullet,transform.position,transform.rotation);
Bullet.rigidbody.AddForce(transform.forward*speed);
Debug.Log (“BulletFired”);
// DamageEnemy();
}
// void DamageEnemy()
// {
// CharacterScript e = gameObject.GetComponent();
//
// e.TakeDamage(10);
//
//
// if (e.GetHealth() <=0)
// {
// Destroy (gameObject);
//
// }
// }
void OnCollisionEnter(Collision col){
if (col.gameObject.CompareTag(“Enemy”)){
// call the function TakeDamage(10) in the hit object, if any
col.gameObject.SendMessage(“TakeDamage”, 10, SendMessageOptions.DontRequireReceiver);
}
Destroy(gameObject); // bullet suicides after hitting anything
}
}
////////////////////////////////////////////////////////////Bullet script