Hi guys im having trouble with my turret, it cant follow nicely to the enemy instead it will straight snap to the direction of the enemy.
Below is my tower script
using UnityEngine;
using System.Collections;
public class Tower : MonoBehaviour {
public float turnSpeed = 2.0f;
// bullet
public Bullet bulletPrefab = null;
// interval
public float interval = 2.0f;
float timeLeft = 0.0f;
// attack range
public float range = 10.0f;
public float range2 = 12.0f;
// price to build the tower
public int buildPrice = 1;
// rotation
public float rotationSpeed = 12.0f;
Transform myTransform;
void Awake(){
myTransform = transform;
}
Teddy findClosestTarget() {
Teddy closest = null;
Vector3 pos = transform.position;
// find all teddys
Teddy[] teddys = (Teddy[])FindObjectsOfType(typeof(Teddy));
if (teddys != null) {
if (teddys.Length > 0) {
closest = teddys[0];
for (int i = 1; i < teddys.Length; ++i) {
float cur = Vector3.Distance(pos, teddys*.transform.position);*
float old = Vector3.Distance(pos, closest.transform.position);
if (cur < old) {
closest = teddys*;*
}
}
}
}
return closest;
}
void Update() {
// shoot next bullet?
timeLeft -= Time.deltaTime;
if (timeLeft <= 0.0f) {
// find the closest target (if any)
Teddy target = findClosestTarget();
if (target != null) {
// is it close enough?
float distance = Vector3.Distance(myTransform.position, target.transform.position);
* if (distance <= range2) {*
_ myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(myTransform.position - target.transform.position), Time.deltaTime * turnSpeed); _
* }*
* if (distance <= range) {*
* // spawn bullet*
GameObject g = (GameObject)Instantiate(bulletPrefab.gameObject, myTransform.position, Quaternion.identity);
// get access to bullet component
Bullet b = g.GetComponent();
// set destination
b.setDestination(target.transform);
// reset time
timeLeft = interval;
}
}
}
}
}