- Home /
How can I check if my Player leaves a Sphere?
Hello there. I am currently working on my first unity-project (3D). So far i have a working CharacterController and an Enemie which is Patroling if the Player is outside of a given sphere around the enemie. If the Player enters the Sphere, the enemie starts chasing the player until he leaves the sphere again. All that works perfectly fine, but i dont like that the enemie starts patroling right away after the player leaves the sphere. I want it to stand still for a moment (and later animate to look around). To achieve that, i have to chech if and when the player leaves the sphere. I obviously already have a bool which checks if the player is inside the sphere or outside, but i have no idea how to check when the bool turns from true to false again.
Im looking forward for a few helpfull answers
best regards, Sakul156
Thanks in Advance! :)
Answer by Earthshine · May 20, 2021 at 08:01 PM
You just need a flag. Let it be bool isChasingPlayer for Enemy chasing Player.
If (Player is inside the sphere and isChasingPlayer is false)
{ isChasingPlayer becomes true;
Enemy stops all coroutines;
and starts the chasing coroutine }
If (Player is outside the sphere and isChasingPlayer is true)
{ isChasingPlayer becomes false;
Enemy stops all coroutines;
and starts looking around coroutine }
When looking around coroutine ends, Enemy restarts the patrolling coroutine.
Thank you, i used your "Code" for inspiration and managed to making it work. Thanks a lot for all the help, guys!
best regards
Sakul156
It was kinda confusing for me to read someone else's code when I had started learning unity, so I decided to just convey the logic instead. I hope reading this 'code' wasn't too much of a headache for you.
Answer by amiel_ace · May 20, 2021 at 02:20 PM
You should look at OnTriggerExit and OnTriggerEnter, from there you can set your bool
hay, thanks for the fast answer. I started watching a video about those triggers and he said that i need to have a rigidbody. The problem is that i dont use a rigidbody in the project.
Well, I must say, that using a rigidbody is so much easier for that purpose. But if you're really insisting in not using a rigidbody, What you can do is use and provide Physics.SphereCast, and place that in a coroutine for manually a constant checking that Physics.spherecast.
Thats actually what im doing:
PlayerInSightRange = Physics.CheckSphere(transform.position, SightRange, LayerMaskPlayer);
But the problem is that i dont know how to check if i leave the sphere. I mean yeah of course the bool turns to false again but i dont know how to include that into a function.
Your answer
Follow this Question
Related Questions
Top Down Shooter Enemy AI using raycasting 1 Answer
Shooting Damage Help 1 Answer
Complete AI Tutorial? 1 Answer
Enemy Patrol 1 Answer