- Home /
Question by
kekrot · Feb 07, 2017 at 11:41 PM ·
2d gameai2d platformerfield of view
How can I clamp direction of RaycastHit2D?
I'm making enemy AI for a 2D platformer, and right now the enemy's behavior is that it can see you with a raycast if you're in close proximity and not behind an obstacle.
Here's normal behavior if you're right in front of the enemy:
However, right now I can only stand behind the enemy, or far away from front of him, in order to not be seen. Since the enemy only looks either left or right, I don't want him to see me when I'm right over him.
Here's what I'm trying to accomplish:
As you can see, I want the direction of the raycast to be clamped to the inside of the blue lines when the enemy is facing the player, while the player is outside of the enemy's field of view.
Here's the code I've written so far.
bool facingRight;
LayerMask colliderMask;
bool inBattle; // when the enemy has seen you, you're in battle
// LookForPlayer() is called while the player is inside a trigger of the enemy
void LookForPlayer ()
{
Vector2 thisEyes = new Vector2(transform.position.x, transform.position.y + 0.8f);
Vector2 playerEyes = new Vector2(player.position.x, player.position.y + 0.8f);
float distance = Vector2.Distance(thisEyes, playerEyes);
// check if player is in front of enemy
if (facingRight && thisEyes.x < playerEyes.x || !facingRight && thisEyes.x > playerEyes.x)
{
RaycastHit2D hit = Physics2D.Raycast(thisEyes, dir, distance, colliderMask);
Debug.DrawRay(thisEyes, dir, Color.red);
if (hit.collider == null)
return;
if (hit.collider.CompareTag("Player"))
{
Debug.Log(hit.collider.tag); // confirm what did the ray hit
inBattle = true;
}
else
{
Debug.Log(hit.collider.tag);
inBattle = false;
}
}
else
inBattle = false;
}
insidefov.png
(2.8 kB)
outsidefov.png
(2.7 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612110554im_/https://answers.unity.com/themes/thub/images/avi.jpg)