I am trying to make a tower defence game. My first objective is how to give a turret it’s radius and if a enemy is within that radius it will attack.
This is attached to a cube called Turret.
using UnityEngine;
using System.Collections;
public class cannonTurret : MonoBehaviour {
[SerializeField]
public GameObject cannonBall;
void Fire()
{
Instantiate(cannonBall, transform.position, transform.rotation);
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Space))
{
Fire();
}
}
}
While after much trial and error, I found the working enemyChaser which is (in prefab):
using UnityEngine;
using System.Collections;
public class enemyChaser : MonoBehaviour {
private Transform targetEnemy;
[SerializeField]
public float projectileSpeed;
// Use this for initialization
void Start () {
targetEnemy = GameObject.FindGameObjectWithTag("Enemy").transform;
}
// Update is called once per frame
void Update () {
transform.LookAt(targetEnemy);
this.rigidbody.velocity = transform.forward * projectileSpeed;
}
}