I need some help on Player detection and AI detection
What I want is the Enemy to detect not only the player, but also Allies of the player, I took a crack at it but haven't gotten anything that works the way I want (If at all). Any tips or Solutions? This is the general idea of what I want
{
public bool noticedSomeone;
//public float fieldOfVision;
public Transform target;
public Collider DetectArea;
public float detectAreaRad;
private void Awake()
{
DetectArea = GetComponentInChildren<Collider>();
}
//What I want it to do:
//If something Stays in the detect sphere, check if it is an Ally of the Player
//Find out its angle relative to the AI, check if the angle is within the correct range
// Create a Raycast to check if it hits
//Set that AI as detected
void OnTriggerStay()
{
if (GetComponent<Collider>().tag == "Ally")
{
target = GetComponent<Transform>();
}
Vector3 targetDir = target.position - transform.position;
float targetAng = Vector3.Angle(targetDir, transform.forward);
//Im pretty sure this is redundant
RaycastHit detected;
Ray detectRay = new Ray(transform.position, transform.forward);
if (Physics.Raycast(detectRay, out detected, detectAreaRad))
{
if (targetAng < 135 && targetAng > 45)
{
if (detected.collider)
{
Debug.Log("I SEE YOU");
}
}
}
}
Answer by ZUrbina · Sep 22, 2020 at 09:10 PM
Sorry about this lol! Turns out it wasn't working because I put the sphere collider in the wrong spot! Late nights will do that to you! It works mostly like I wanted it too, just a few tweaks, but thanks anyways!
Answer by streeetwalker · Sep 22, 2020 at 05:15 AM
Where does this script reside, on the Allies you are trying to detect? If not, where? If it not attached as a script component on the Ally GameObjects, then it doesn't make any sense.
For example GetComponent as is in the code gets the component of the object the code resides on. Furthermore, GameObjects have tags, not components. The tag can be gotten directly from the collision object that is passed to the trigger event handler, so there is no need to do a separate call GetComponent - see the OnTriggerStay documentation.
There are quite a few things that potentially wrong in the code, but we need to know what the set up of game is - where does the above script sit, and what objects have trigger colliders on them.
Your answer
![](https://koobas.hobune.stream/wayback/20220613012320im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to prevent usage of a non-supported platform effect ? 0 Answers
How to detect if the player is not moving 1 Answer
Check for collision ONCE 0 Answers
How to detect computer volume? 0 Answers
Randomly play multiple attack animation 0 Answers