I am building a tower defense, and I want to upgrade my turrets. I’ve been trying to use OnMouseUp and raycasting, but both have failed. When using OnMouseUp, it doesn’t matter where I click, it will run the function anyways. And when using raycasting, the same thing happens, or nothing will happen at all.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
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;
public GameObject aimHere;
public List<GameObject> targetList = new List<GameObject>();
public float damage;
public RaycastHit hit = new RaycastHit();
public Ray ray;
protected bool showUpgrades;
private float nextFireTime;
private float nextMoveTime;
private Quaternion desiredRotation;
private float aimError;
void Start() {
damage = 12.5f;
showUpgrades = false;
}
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();
}
}
if(target == null && targetList.Count >= 1) {
target = targetList[0].transform;
aimHere = target.gameObject;
}
}
void OnTriggerEnter (Collider other){
if(other.gameObject.tag == "AimPoint") {
nextFireTime = Time.time + (reloadTime * .5f);
// target = other.gameObject.transform;
targetList.Add(other.gameObject);
}
}
void OnTriggerExit (Collider other){
if(other.gameObject.tag == "AimPoint") {
targetList.Remove(other.gameObject);
}
}
void CalculateAimPosition (Vector3 targetPos){
//Vector3 aimPoint = new Vector3(targetPos.x + aimError, targetPos.y + aimError, targetPos.z + aimError);
Vector3 aimPoint = new Vector3(aimHere.transform.position.x, aimHere.transform.position.y, aimHere.transform.position.z);
if (aimPoint != turretBall.position) {
desiredRotation = Quaternion.LookRotation(turretBall.position - 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);
}
}
public void TargetIsDead() {
Debug.Log("TargetIsDead");
targetList.RemoveAt(0);
FetchNextTarget();
}
void FetchNextTarget() {
Debug.Log (targetList.Count);
}
void OnMouseUp() {
if(showUpgrades) {
showUpgrades = false;
} else {
showUpgrades = true;
}
}
void OnGUI() {
if(showUpgrades) {
if(GUILayout.Button("Upgrade")) {
damage = damage + 10;
Debug.Log("Upgraded");
}
}
}
}