yassin eltaramsi
yassin eltaramsi

Reputation: 59

3D Unity - Implementing a raycast visibility test with "peripheral vision"

Background: I am making a 3D unity game with a player and an enemy AI using navmesh. The way it's supposed to work is that when the player is in the sight range of the enemy, it chases him, and when the player is in the attack range, the enemy shoots him.

The problem: The way I used to do visibility testing (to check if the player is in sight/attack range) is by using a physics.overlapsphere, but this method has it so that the sphere goes through the walls, meaning the player can be within sight range, even if there is a wall between the enemy and player. I now have a raycast system in place (code snippet for that below) but my issue with it is that the player has to be DIRECTLY in front of the enemy to be within sight range, when I want him to also be able to detect the player through his "peripheral vision." Does anyone have any idea on how to implement this kind of thing?

raycast code

I will do my best to answer any questions and any help would be greatly appreciated.

Upvotes: 0

Views: 286

Answers (2)

TimChang
TimChang

Reputation: 2417

// detectDistance is your detect radius.
if ( Vector2.Distance(enmeyPos - playerPos) <= detectDisctance )
{
   new Ray(playerPos, enemyPos - playerPos)
   // if ray on wall , ignore it.
   // todo
}

Upvotes: 0

JonasH
JonasH

Reputation: 36371

You should be creating a ray from the player towards the enemy, i.e.

new Ray(playerPosition, enemyPosition - playerPosition)

You might also want to send multiple rays, like send a ray towards each corner of the enemy bounding box. Or send a bunch of rays from each of the eyes of the enemy toward randomly selected points on the player. This should help improve accuracy, since neither the player nor the enemy are point sized objects that could potentially be occluded by a tiny object.

Upvotes: 0

Related Questions