- Home /
Raycast from inside an object
I'm building the code for a gun right now and the code works fine as in it applies the appropriate damage to an enemy hit. What I'm considering doing though is giving certain weapons pierce the enemy and hit any behind it. My idea was to cast a ray out from the point that the first ray hit the enemy and check if it hit a different enemy.
My thing is the logic in my head is telling me that casting it from the hit spot would collide with the enemy I just shot and do additional damage to it instead of any enemies behind it. I suppose I could avoid that by moving the rays start point a little bit on the forward transform where I would cast it from there but I want to know is if the start point happens to be inside the enemy, will it still collide with the first enemy or will it not return a hit until it hits a new enemies collider (or any walls behind them)?
Answer by robertbu · Aug 16, 2014 at 10:18 PM
For 3D colliders, a raycast against the backside of any mesh will not record a hit. So if you were inside a sphere or a cube, your Raycast would not hit the object the start position was inside. But you have to be careful. Imagine an enemy with hands and arms. Say your hit point was a hand, and you moved the ray a bit inside the hand. It is possible for the new ray to travel out of the hand but hit the front side of the body or face of the same enemy.
A better solution is to use Physics.RaycastAll(). Not the hits are not guaranteed to be sorted when using RaycastAll(), so you need to process the hits to figure out the order of the hits.
I see what you mean about the body parts. That slipped my $$anonymous$$d because right now my enemies are all in the block in stage and nothing more than giant capsules. It wouldn't be a problem if I left the overall collider a capsule but there's a number of reasons why I wouldn't do that. I'll look into he raycastall. I want the pierce to be limited depending on the weapon (pierces once for assault rifle, 2 maybe 3 times for sniper, etc) so I am a bit worried about the return order though.
Answer by Adam_Benko · Jun 25, 2021 at 12:17 PM
Spawn a cube with collider at the impact site. Move it in direction of the bullet. Use on trigger exit method to get the back side of character.