Raycast 2d Isn't going Like I want it to

Hi, I’m currently working on a 2D slingshot game. I’m using the player transform and a Direction transform in front of the player to draw a Raycast to detect where the player should go but after I moved the first time it just not working at all.
I recorded a short clip to show the error:

7037947–834358–ChildrenController.cs (1.66 KB)

You named your variable “direction” but that doesn’t make it a direction, it’s a point in space.

Here’s the docs for Physics2D.Raycast. The 2nd argument is a direction not a position in space. In your case it’s a normalized “direction - startPos” but be careful here as those are 3D vectors. You should use 2D vectors otherwise any differences in Z can throw it out.

There’s Physics2D.Linecast which performs a check on a line-segment.

1 Like

Thx, but I still don’t quite know how to do it. Im completely new to raycasts and vectors and stuff so a small example would be nice.
And Im using Vector2, aren’t they 2D Vectors?

Okay but that’s why we have docs. You specify a start position, direction, distance and mask.

        startPos = playerTrans.position;
        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        direction = (mousePos - startPos).normalized;

        RaycastHit2D WallCheck = Physics2D.Raycast(startPos, direction, Mathf.Infinity, ground);

Also note that unless you are absolutely sure this raycast will hit something, you should check to see if it does with “if (WallCheck) { }”

Sorry yes, I just saw that you were transferring the Vector3 Transform.position to Vector2.

1 Like

Thank you so much