Hey fellas,
I am working on a doom-esque fps, and I have a turret enemy that instanciates prefab bullets
and each of those is being propelled via vector.forward.
The prefab turret also has two If Statements’, one to control distance and another to only fire at the player when he is not behind a collider.
Also the turret uses a Quaternian Slerp to slowly rotate towards the player while firing
at the same time.
The prefab itself is structured as such:
--wallBot=Empty GameObject
----botModel= Model of the turret
----botLight= Spotlight
----botCollider= To test collision with bullets
Here be code:
using UnityEngine;
using System.Collections;
public class BotWall : MonoBehaviour {
public Transform trget;
public Transform meTransform;
public int maxSeeDistance;
public GameObject alarmLight;
public float meTransY;
public int rotationSpeed;
public Transform botBullet;
public GameObject botSpitfire;
public Transform bulletModel;
public int botBulletSpeed;
public int botBulletInterval;
public int wallBotHealth;
private int bulletTime;
void Awake () {
meTransform = transform;
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
trget = go.transform;
meTransY = meTransform.rotation.y;
GameObject.Find("wallBot_spot").light.intensity = 0;
}
void OnTriggerEnter (Collider coll)
{
if(coll.tag == "Bullets") {
wallBotHealth --;
if (wallBotHealth <= 0)
{
Destroy(gameObject);
}
}
}
void Update () {
if ((Vector3.Distance(trget.position, meTransform.position)) < maxSeeDistance)
{
if (Physics.Linecast(meTransform.position, trget.position))
{
//Debug.Log("Clear line of sight");
meTransform.rotation = Quaternion.Slerp(meTransform.rotation, Quaternion.LookRotation(trget.position - meTransform.position), rotationSpeed * Time.deltaTime);
GameObject.Find("wallBot_spot").light.intensity = 7;
Debug.DrawLine(trget.position, transform.position);
bulletTime ++;
//bullet counter, to create a delay between each bullet
if (bulletTime > botBulletInterval)
{
GameObject.Find("wallBot_spot").light.intensity = 8;
Transform botBullet=(Transform)Instantiate(bulletModel, (transform.position - new Vector3(0.7f, 0f, 0f)), Quaternion.identity);
botBullet.rigidbody.AddForce(transform.forward * botBulletSpeed);
//reset counter
bulletTime = 0;
}
}
}
else
{
Debug.Log("Out of reach");
meTransY = 180;
GameObject.Find("wallBot_spot").light.intensity = 0;
}
}
}
I bet the keen eyed folks here can tell that since this is structed as such I cannot scatter
this enemy around and have it work.
Basically I would like to know how to create this efficiently so I could scatter
it around without having it be half broken(light goes on one bot but not another etc).
And how to make the enemy wall bot not shoot at the player when he is behind a collider,
since right now it doesnt seem to work…