Hi, I’m making a first person game and I came across this weird problem, I’m casting a ray out from the camera to detect what the character is looking at, so I made a block and when the character look at the sides of that block the ray detects it, but when I jump ontop of the block and look down at it the ray no longer detects the block even though the ray goes through it. Why is that?
Here is my code.
RaycastHit hit = new RaycastHit();
void Update () {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(transform.position, transform.forward, out hit, raycastDist))
{
if(hit.collider.gameObject.CompareTag("Chest"))
{
Debug.DrawRay(transform.position, transform.forward * 100,Color.red);
print ("(E) Open Chest");
onChest = true;
}
else
{
Debug.DrawRay(transform.position, transform.forward * 100,Color.red);
print ("Not hitting anything");
onChest = false;
}
}
}
You need to set a layer mask on the raycast so it will not hit the player: assign to the player gameobject a custom layer and then set the layerMask parameter to the RayCast.
You can create a layer mask by using
int layermask = 1 << 8; // consider just the layer defined at the index 8 of the layers array
the number 8 is the first of the custom layer. If you are using the predefined IgnoreRaycast layer your code should be:
int layermask = 1 << 2;
If you instead want to collide with everything except a particular layer you have to use:
int layermask = ~(1 << 8); // consider all layer but the one defined at number 8
<< is a binary shift operation while ~ is the negation of that operation. You can combine more layers just using the binary operation on different masks.
No. That makes no sense, the camera can’t see the player. The reason it is happening is because you are casting a ray from the world position of the player.
Like I said, you are creating a Ray object, but you are not using it in your Physics.RayCast.
A CapsuleCollider is not a SphereCollider… but anyway, I’ll do a little test project and I’ll let you know
Thanks for pointing me to the unity script reference.
I think “sphere” is a misnomer. I’ve achieved the same result with a variety of collider types. However - I believe a CapsuleCast or SphereCast will return its containing collider.