- Home /
Enemy AI scripting help
Hello everybody, I need help with creating a enemy AI, specifically a monster since i am creating a horror game. (note) I am a complete noob when it comes to game developing so bare with me here.(I have recently a scripted an enemy AI but it really didn't meet the specifications that i ask for) The type of AI i want is a monster that will only select you as a target if it touches/ sees you. I have been mostly using youtube tut's on scripting and "basics" of unity, but there doesn't seem to be anything THIS specific on there. So, if you could help me out it will be GREATLY appreciated. Here is the Script the enemy AI i made off the youtube video I used maybe it can be revised so it can do what i want it to do.
using UnityEngine; using System.Collections;
public class EnemyAI : MonoBehaviour { public Transform target; public int moveSpeed; public int rotationSpeed;
private Transform myTransform;
void Awake() {
myTransform = transform;
}
// Use this for initialization
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");
target = go.transform;
}
// Update is called once per frame
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
//Look at target
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Answer by robertbu · Feb 19, 2013 at 05:24 AM
Here is a step in the direction you are going. You can use Physics.LineCast() between your enemy and your player. If it returns something other than the player in the cast, you know a collider is between the middle of your enemy and the middle of your player. This is not a perfect solution, but might be good enough depending on your game.
void Update () {
Debug.DrawLine(target.position, myTransform.position, Color.yellow);
RaycastHit hit;
if (Physics.Linecast(myTransform.position, target.position, out hit)) {
if (hit.collider.tag == "Player")
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
}
//Move towards target
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613092942im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to reach multiple GameObjects' value , enemy AI 1 Answer
Make player not be seen by AI, when player in foilage and shadows. 1 Answer
Enemy AI C# 0 Answers
Enemy Avoid Terrain 0 Answers
Why doesn't this AI script work? c# 1 Answer