# Cast ray from one specific object to another

I’m trying to set up a situation where an enemy game object continuosly checks to see if the player object is “visible” if it is within a certain distance of the player. In other words, I want to make it so the enemy will not start chasing/attacking the player if there is a physical object between the player and the enemy (such as a wall in the level) that would block the enemy from seeing the player and therefore knowing that the player is even there.

If there is an easy way to just provide two objects and have unity cast a ray from one to the other, I haven’t found it. So far as I can tell I have to somehow find otu what direction the player is in relative to the enemy’s orientation and provide that direction in a raycast statement. I don’t know how to find that direction though. Ideas?

Hm maybe this will work:

``````float maxRange = 5;
RaycastHit hit;

if(Vector3.Distance(transform.position, player.position) < maxRange )
{
if(Physics.Raycast(transform.position, (player.position - transform.position), out hit, maxRange))
{
if(hit.transform == player)
{
// In Range and i can see you!
}
}
}
``````
10 Likes

–Eric

4 Likes

Well I’ll be dipped. Thanks. This’ll make life a lot easier.

Actually, there’s a bit of a problem. If you read the description of linecast it says it looks to see if a line going from the one object to the other intersects anything else in between. I would have thought that I should still be able to use this to tell if the enemy could see the player by just reversing the logic ( or make it so the enemy only sees the player if linecast returns false). However linecast seems to return true whether or not there are any objects between the player and the enemy, and I can’t figure out why.

Actually, I think I might know why. I think the enemy and player meshes are probably the colliders in the way. If I understand correctly I just need to figure out how to use this layermask doohicky.

yes you could use layermasks, or you simply do this:
(not spellchecked, pseudocode)

``````source.layer = 2; //IgnoreRaycast Layer
target.layer = 2;

linecast (...) // as mentioned above

source.layer = 0; //Normal Layer
target.layer = 0;
``````

additionally, you should decide if you really NEED the
“out hintinfo”, because if you only want to see IF there are obstacles - and not, where exacrly they are,
you should use the overload method where no hitinfo is provided because this makes a difference in performance.

hope than helped

Nice code, but instead of multiple IF’s you could’ve done it in one IF with using “&&”.

1 Like

This worked perfectly for me!! Thank you.

This only works if the object your using to raycast to another is at world position of 0, 0 ,0