2D Raycast Problems

Hey, I’m trying to create a simple 2D shooter but there’s a problem with my characters shooting. It seems that the raycast cannot find the right hit position as you can see in the pics.

Edit #1: I made the scene barebone simple and still cannot hit.
Edit #2: I uploaded project with just three files (scene, character control script and a character sprite) and the problem persists. Cannot get simpler than this.

Especially rotated GameObjects give weird results. What’s going on? I’m feeling there some minor detail really missing here… getting blind for the whole situation since it’s been x hours solving it.



3777973–316192–raycast_problems.unitypackage (7.96 KB)

Quite simply you’re using Physics2D.Raycast wrong. If you look at the docs you’ll see the first two arguments are start position and direction; you’re passing start position and end position.

If you want to check a line with a specific start and end position then change your query to Physics2D.Linecast and it should work fine like so: Screen capture - 17bcd53c744cab1f9d5d622b3440926c - Gyazo

1 Like

Oh yes, that’s it. In my case I have to use raycast and direction was indeed the messed up part. Thanks a lot!

Vector2 position = transform.position;
Vector2 direction = transform.right;
RaycastHit2D hit = Physics2D.Raycast(position, direction);
1 Like