I am building a tower defense game, but with my code, the tower faces -180 degrees away from the target. Why?
using UnityEngine;
using System.Collections;
public class Cannon : MonoBehaviour {
public GameObject projectile;
public float reloadTime = 1f;
public float rotateSpeed = 5f;
public float cooldown = .25f;
public GameObject muzzleEffect;
public float errorAmount = .001f;
public Transform target;
public Transform[] muzzlePositions;
public Transform turretBall;
private float nextFireTime;
private float nextMoveTime;
private Quaternion desiredRotation;
private float aimError;
void Update (){
if(target) {
if(Time.time >= nextMoveTime) {
CalculateAimPosition(target.position);
turretBall.rotation = Quaternion.Lerp(turretBall.rotation, desiredRotation, Time.deltaTime * rotateSpeed);
}
if(Time.time >= nextFireTime) {
FireProjectile();
}
}
}
void OnTriggerEnter (Collider other){
if(other.gameObject.tag == "Enemy") {
nextFireTime = Time.time + (reloadTime * .5f);
target = other.gameObject.transform;
}
}
void OnTriggerExit (Collider other){
if(other.gameObject.transform == target) {
target = null;
}
}
void CalculateAimPosition (Vector3 targetPos){
Vector3 aimPoint = new Vector3(targetPos.x + aimError, targetPos.y + aimError, targetPos.z + aimError);
desiredRotation = Quaternion.LookRotation(aimPoint);
}
void CalculateAimError (){
aimError = Random.Range(-errorAmount, errorAmount);
}
void FireProjectile (){
//audio.Play();
nextFireTime = Time.time + reloadTime;
nextMoveTime = Time.time + cooldown;
CalculateAimError();
foreach(Transform theMuzzlePos in muzzlePositions) {
Instantiate(projectile, theMuzzlePos.position, theMuzzlePos.rotation);
Instantiate(muzzleEffect, theMuzzlePos.position, theMuzzlePos.rotation);
}
}
}
↧