- Home /
How do I get my emeny AI to detect if he sees a player, or one of the good AI? (C#)
I'm having a problem with getting my Enemy AI to detect my player, or any of the good AI.
I'm trying to make it so that if the enemy AI sees the player, or one of the good AI, it goes after it.
I can't get it working, though. Even if I stand right in front of the enemy, he doesn't see me, and doesn't move.
Here's my code:
RaycastHit hit;
Vector3 directionOfLine = myTransform.TransformDirection(Vector3.forward);
Debug.DrawRay((myTransform.position + (Vector3.up * 6) + (Vector3.forward * 4)), directionOfLine * range, Color.red);
if (Physics.Raycast((myTransform.position + (Vector3.up * 6) + (Vector3.forward * 4)), directionOfLine, out hit, range))
{
if (hit.rigidbody.tag == "Player" || hit.rigidbody.tag == "Rossi Comrade")
{
target = hit.transform;
targetInSight = true;
}
}
(The model origin is on their feet, so it's got "Vector3.Up." added to it to put the line origin at the head)
What am I doing wrong?
Log inside raycast and tell if you see if this log prints out in console. Dont put log inside "if (hit.rigidbody.tag" but before - to check if raycast hit anything:
if (Physics.Raycast((myTransform.position + (Vector3.up * 6) + (Vector3.forward * 4)), directionOfLine, out hit, range)) {
Debug.Log("BOO$$anonymous$$!");
if (hit.rigidbody.tag == "Player" || hit.rigidbody.tag == "Rossi Comrade") {
target = hit.transform;
targetInSight = true;
}
}
It registers and logs it, but it still does nothing when the raycast hits the player.
Answer by Cobradabest · Jan 25, 2013 at 07:49 PM
I got it working, it turns out the player doesn't have a rigidbody, but a Chaacter controlelr, so I changed it to hit.collider, and it worked!
Answer by jorjdboss · Jan 24, 2013 at 11:00 AM
// Parent an empty gameobject called eye and
// place it at the eye of the AI object with the z axis facing forward
public Gameobject eye;
public float viewDistance = 10f;
public RaycastHit hitInfo;
Physics.Linecast( eye.transform.position, eye.transform.position + (eye.transform.forward * viewDistance), out hitInfo );
// Test out by making the rigidbody isKinametic = true and manually dragging the AI to front of player/ good AI
Debug.Log(hit.collider.tag);
Code not tested but hope it helps.
Answer by ynka · Jan 24, 2013 at 11:36 AM
Are layers configured properly? Can enemy and player see each other? Maybe layer is ignoring raycasts.
Your answer
Follow this Question
Related Questions
Enemy Spawn Script Spawning Infinite Enemies [Help] 2 Answers
Make player not be seen by AI, when player in foilage and shadows. 1 Answer
Make AI walk around randomly until Player is Seen. (C#) 2 Answers
how can i make the enemy kill more players one after the other chasing them ??? thank you 0 Answers
have friendly AI look at enemy 0 Answers