- Home /
Enemy Line of Sight Help Needed
I am making a 2d top-down stealth game and I have an enemy character that patrols waypoints. I have a 2Draycast that looks in the direction that the enemy is looking. The problem is that once my enemy character reaches the waypoint, the raycast just disappears. I have a feeling my direction variable is the reason why this is happening, but what alternatives do I have to ensure the 2Draycast faces in the direction faces in the direction the enemy is facing and that it does not disappear?
void CanSeePlayer(){
direction = (moveSpots[nextPosition].position - transform.position).normalized;
RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, distance);
Debug.DrawLine(transform.position, transform.position + direction * distance, Color.blue);
}
And below will be my patrol function, which may be helpful for anyone answering.
void Patrol(){
transform.position = Vector2.MoveTowards(transform.position, moveSpots[nextPosition].position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, moveSpots[nextPosition].position) < 0.5f)
{
if (waitTime <= 0){
nextPosition = (nextPosition+1) % moveSpots.Length;
waitTime = startWaitTime;
}
else{
waitTime -= Time.deltaTime;
}
}
}
Both are called in Update.
Answer by Caeser_21 · Mar 27 at 10:16 AM
What happens if you just do :
nextPosition++;
Instead of :
nextPosition = (nextPosition + 1) % moveSpots.Length;
Based on your comment you can do something like :
nextPosition++;
if (nextPosition > moveSpots.Length)
{
nextPosition = 0;
}
Answer by sajidsyed201 · Mar 27 at 11:35 AM
I get a null exception. My enemy is supposed to move back and forth on it's path and continuously increasing nextPosition will not allow for that.
Your answer
![](https://koobas.hobune.stream/wayback/20220613054649im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How do I make a Hollow square 0 Answers
One 2D Raycast Being Weird While Others Work 0 Answers
2D Top down physics with ground (slippery floor...) 1 Answer