- Home /
Make enemy to "see" player in Unity 2d
Hello,
I'm making top down game (Hotline Miami style).
My problem is: how to make raycast or linecast (to detect player) form enemy eyes. Enemy can turn to face player after he detect him, so raycast from must rotate with enemy to emulate enemy vision direction.
To explain more: My problem is: how to draw a raycast in front of the enemy (just like from enemy's eyes), and rotate it when enemy rotates.
Checking if a character see something is not a problem.
Your question is unclear. If you want to check if a character "sees" something is, like you said, to use a raycast (see Raycast2D
I'm unclear what you are actually asking. Could you explain further?
$$anonymous$$y problem is: how to draw a raycast in front of the enemy (just like from enemy's eyes), and rotate it when enemy rotates.
Checking if a character see something is not a problem.
A raycast ray usually has a direction for casting. whatever forward your character is using (in 2D might be y if you start looking up in the top down game if the camera is not acutally looking dawn in 3D), use it as the direction. If you need to be more precise on the origin, use the position of the characters eyes for example.
RaycastHit2D hit = Physics2D.Raycast((Vector2) transform.position, (Vector2) transform.up);
should do the trick
Unfortunately
RaycastHit2D hit = Physics2D.Raycast((Vector2) transform.position, (Vector2) transform.up);
does not work for me. I don't know how to change raycast lenght. Also raycast collide with enemy body, and do not hit the player.
To be more precise here is the picture:
enemy always starts facing "Up" on y-axis,
Raycast turns with enemy,
I want to be able to change raycast lenght,
Thanks,
you could attach the raycast to a empty game object just infront of where u think the eyes will be
Answer by P.W. · Feb 14, 2015 at 01:49 PM
Ok, i upgrade the solution with 'fov' and simple vision cone form my enemies.
distanceToPlayer = Vector3.Distance ((Vector2)transform.position, (Vector2)playerPosition.position);
angle = Vector2.Angle (transform.up, playerPosition.position - transform.position);
if (distanceToPlayer < rng) //range = known float
{
playerInRange = true;
if(angle < fov*0.5f) //fov = know float
{
// do something
}
It's worked form me well.
Thanks everybody for answer.
Answer by ryandotdee · Feb 12, 2015 at 03:07 PM
transform.forward will give you the direction the object is facing
RaycastHit2D hit = Physics2D.Raycast((Vector2) transform.position, (Vector2) transform.forward, distance);
http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
3rd argument is distance ( length)
Answer by brentshermana · Aug 10, 2015 at 04:04 AM
Contrary to what ryandotdee says, in top-down perspective it's transform.up that gives you the direction your character is pointing (provided that the original imported sprite is facing upwards)
Similarly, a sprite which faces downwards in the sprite sheet would use transform.down
Your answer
