In my project, I have an enemy that needs to be able to check if the player is in line of sight, as well as some other things, and I decided to do it with Raycasting, but with layer masks. The player has a child that basically works as the collider for “sight”. This child object is in Layer 8, labeled “Sight”.
Here’s some images to demonstrate:
Entire PlayerCharacter selected, tagged played with no layer.
So the problem is, the enemy’s script that’s supposed to fire isn’t working. Specifically, the Raycast I send out towards the players direction 5f long won’t “hit” the sightbox. At one point it was hitting the Player, but that’s not what I wanted and I don’t even know HOW it was doing that because it should only be hitting things on the Sight layer.
Here’s my code. I’m POSITIVE there’s just a problem with how I’m handling my arguments but I’m just not sure what I should be doing to fix it.
LayerMask sightMask = LayerMask.GetMask("Sight");
Debug.DrawRay(transform.position, -(transform.position - player.transform.position).normalized * 5, Color.green);
if (Physics.Raycast(transform.position, -(transform.position - player.transform.position), out sightRayHit, 5f, sightMask)) {
Debug.Log("Hit " + sightRayHit.transform.name);
if(sightRayHit.transform.name == "PlayerSightHitbox") {
//This is where stuff is supposed to start happening, but nothing I put in here works. Literally nothing.
}
}
Any help would be appreciated. I’m just trying to fix this so I can move on and keep learning but I’ve been stuck here for a good long while.
Make a blank scene and strip it down to isolate what is going on. Remove ALL the player geometry, etc., just have your casting script on an invisible GameObject and a “Sight” marked cube, maybe a few others to see what is going on.
Once you get that working, start working back to where you are. I seem to recall oddness when you started from inside a collider and specified layers, so one possible idea is to disable all colliders on the player, do your raycast, then re-enable them all, something I have occasionally had to do.
Also, are you seeing the Debug.DrawRay() and is it where you expect it to be?
Never got back to this thread but I wanted to say that I was able to figure out by stripping the game down to its basics. I didn’t remove ALL geometry, etc, but I stripped it down to bare essentials for that system, and I was able to compare and debug the issue.
Turns out, having a rigidbody on the PARENT component tags the PARENT as things (thing?) the child was, which is why the player was being read as part of sight and why the Sightbox was never being hit- it was being “hit” as the PlayerCharacter.
Thanks for the advice man. Teach a man to fish, right?