How can I tell what the tag of an object a RayCast hits is?
I need this script for a stealth FPS game. The way my current scene works is that there is a guard that has a collision field and if your in the field the guard shoots a RayCast at you to see if you are behind cover and if you aren’t it will shoot at you. I’ve done some research and can’t seem to find any help on this topic that is well explained in how it works for instance why are “ray” and “hit” always used as variables when one is supposed to be an origin point but they define it as a direction? i just need help to understand what i need to do to check if the tag of an object hit by a RayCast is the tag “Player” which is on all the objects associated with the player.
Physics.Raycast has several overloaded methods. Generally you should choose whichever one you need to get the job done. IE: do you need a particular distance, to ignore certain layers, get the hit information?
I would assume you want to do this:
GameObject gun;
GameObject guard;
Ray ray = new Ray(gun.transform.position, guard.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.tag.Equals("Player"))
{
// hit player
}
}
Ray just combines the starting point and the direction and RaycastHit holds tons of information. Although the next part is figuring out where does the raycast need to hit the player to determine if he is seen - since the player could be partially hidden.
Edit for UnityScript version (thanks Landern):
var gun : GameObject;
var guard : GameObject;
var ray = new Ray(gun.transform.position, guard.transform.forward);
var hit : RaycastHit ;
if (Physics.Raycast(ray, hit))
{
if (hit.collider.tag.Equals("Player"))
{
// hit player
}
}