You have to create a script to tell what are directions. Once you have created that. You need to create another class to check that if enemy or game character left/right/front/back is wall don’t shoot.
I’m thinking of that too as last resort but yeah Raycast would be idea. Good suggestions.
Here is the finished code for some beginners to use:
The enemy ai would face the player if it was at a certain distance and the ai will face the player if it is behind it but will shoot only if it is the player.
using UnityEngine;
using System.Collections;
public class enemy_ai_c : MonoBehaviour {
public Transform player;
public float range = 50.0f;
public float bulletImpulse= 10.0f;
private bool onRange= false;
public Rigidbody projectile;
public GameObject blaster;
void Start(){
float rand = Random.Range (1.0f, 2.0f);
InvokeRepeating("Shoot", 0.50f, rand);
}
void Shoot(){
if (onRange){
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
if (hit.collider.gameObject.layer == 0) {
Rigidbody bullet = (Rigidbody)Instantiate(projectile, transform.position + transform.forward, transform.rotation);
bullet.AddForce(transform.forward*bulletImpulse, ForceMode.Impulse);
Destroy (bullet.gameObject, 2);
}}}
}
void Update() {
onRange = Vector3.Distance(transform.position, player.position)<range;
if (onRange)
transform.LookAt(player);
}
}
Well, you could use a Raycast to detect the Obstacles in the same range as the Player detection range, and if it finds noting, then Raycast to see if there is a player, and if there is a player, shoot.