I’m making a 2D platformer/shooter, and I’m having an unexpected issue:
I launch bullets by instantiating them at the end of the player’s gun, but the gun does not have collision (this is intended). This means that the gun can partly clip into the walls (which have a tilemap collider 2D). This is fine, but can put the bullet launch point inside the walls. When I shoot in this case, the bullets spawn and travel inside the wall, and only register a collision when they hit the opposite side. This means that, for instance, my ricochet gun bounces WITHIN the wall.
What seems to be happening here is OnCollisionEnter2D is not called immediately if the object starts out within another collider. What I would like is for the bullets to register a collision as soon as they’re shot into a wall, so the ricochet/explosion/etc. happens properly, and no bullets end up inside wall. How can I accomplish this? Thanks!
There’s a few different ways to deal with this edge case. Obviously you want bullets to normally spawn from the tip of your gun so they look correct. But if the tip of the gun can go inside colliders, well, that fails.
One technique is to actually raycast from the player’s center (assuming he can never go in a collider) to the tip of the rifle, raycasting only for walls (use LayerMask to be selective).
Then if you hit a wall, artificially “back up” the launch point from the muzzle to a point far enough outside the wall (you get the impact point in the RaycastHit struct) to register a collision.
Or else use that technique to disable the gun.
Or use that technique to artificially shove your player back away from the wall instead of firing. That will compel users to not get too close to the wall and expect their gun to work.
I like this approach, since yes the player (and therefore the handle of the gun) are guaranteed not to be in a wall. I think simply launching from the player’s center in that case would be sufficient. The other two options don’t work well for me, since recoil-based movement is a key component of the game. I want to always be able to fire, even if it’s into a surface, in order to recoil away from it.