- Home /
How does my raycast work?
This is going to be an odd question as I'm essentially asking why something works, instead of why it could be broke.
I am creating a system in which two objects, a prey and a predator react to each other. In order to get these behaviours working I have had to make sure the objects can 'see' each other. I've begun with my prey object and have a raycast set up, checking for an object in range and then drawing a raycast line in debug to show the path between them. This is all handled within this method
bool HasPreySeenPredator()
{
//code to manage direction of prey and whether predator in range
bool preySeenPredator;
RaycastHit hit;
Vector3 fwd = transform.TransformDirection(1,0,0);
//fwd holds the orientation of the object's 'face'
if(Physics.Raycast(transform.position, fwd, out hit, sightRange))
{
preySeenPredator = true;
Debug.Log("There is something in range. Distance: "
+ hit.distance + ". Object: ");
Debug.DrawLine(transform.position, hit.point);
}
else
{preySeenPredator = false;}
return preySeenPredator;
}
This is put together with the help of the Physics.Raycast references in unity's online help files. I have various objects within my scene to which the raycast does not react to. I have the prey tagged as 'prey' and the predator as 'predator' but haven't used their tags in the code. My other objects are untagged and tagging them as 'predator' does not get the prey's raycast to hit it.
Can anyone explain to me why this works?
Answer by Owen-Reynolds · Feb 22, 2013 at 02:59 PM
Raycasts don't use tags -- they use layers. You probably have everything else in the scene on the ignoreRaycast layer.
To clarify, you can check tags after the ray cast, of what it hits, and you probably want to: "if(phy.rayCst(...) { if hit.CompateTag("prey") ...". But the actual raycast stops at the first collider it hits. You'd never know if prey was behind it.
Layers are uses to make the raycast act like that stuff isn't there. If tigers can "See trough" other tigers, you could make them do that with "phi.rayCst(..., 1<<~(predatLayer || ignoreRCLayer)".
Yeah I also found that the difference between the prey and predator and the other objects was whether they had box colliders. Thanks for the info.
Your answer
Follow this Question
Related Questions
if hit.collide.tag is not working on raycast function 1 Answer
Raycast help 1 Answer
Are tag settings passed down from Game Object parent to mesh child? 1 Answer
rayCastHit question 1 Answer
RaycastHit Collider Question 1 Answer