How to fix RayCast2d not detecting collision?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Weexer

I am working on bullets for my game, bullets detect colliding object with raycast2d, but sometimes it just gets broken. For example: if player moves in exact moment bullet is about to hit player, bullet just clips through him. Right now, my in game turret is shooting towards player standing in the middle of the room, and EVERY bullet clips through him, but i I move, bullets hit me. It’s probably something with bullet travelling so fast that in one frame, raycast is out of range, but in second frame it’s already inside player, so it doesn’t detect collision, I don’t want to make bullet slower, or make raycast longer, how do I fix that?

:bust_in_silhouette: Reply From: jgodfrey

If the problem is caused by the bullet moving “too fast” as you suspect (and, that’s quite possible), one standard solution is to know the bullet’s position over 2 frames (the previous frame and the current frame). Then, just cast a ray between those two positions and see if it hits anything interesting. If it does, treat it as a hit. Otherwise, just ignore it…