Why does my raycast only work when my mouse is in the corner of the game view?

Viewed 27

I'm a beginner programmer and I'm trying to make it so a 2D Raycast with a length of 1 shoots out from the player toward the mouse when you click. Here's my code:

if (Input.GetMouseButtonDown(0))
        {
            Debug.DrawRay(transform.position, mousePosition * 0.1f, Color.red);

            RaycastHit2D hit = Physics2D.Raycast(playerRb.transform.position, mousePosition, 0.1f);

            if (hit.collider != null)
            {
                hit.transform.GetComponent<TreeScript>().treeHealth -= 1;
            }
        }

I'm using the drawray to visualize my raycast, but when I click, it has some funky behavior. First of all, the direction the ray casts starts from the bottom left corner of the game view. So if I click with my mouse directly above the corner, the raycast will shoot straight up from the player. On top of that, the length of the raycast depends on the distance of the cursor from the corner. I want the raycast to be a constant length (so I can detect when the player is close enough to a tree).

1 Answers

Firstly, as mentioned in the comments, second parameter of Raycast is direction, not point, even though both can be expressed by using Vector. In case you don't know how to calculate direction, it's pretty simple: just substract start position (transform.position in your case) from the end (which is mousePosition). The whole expression will look like this:

Physics2D.Raycast(playerRb.transform.position, mousePosition - transform.position, 0.1f);

Secondly, you need to understand a difference between spaces. I suspect, your mouse position is just Input.mousePosition and it will return position in a screen space, whereas your object is in world space. You need to convert one position, so they both are in the same space. Consider this piece of code:

Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("mouse " + Input.mousePosition + " worldPos " + mousePosition);

I'm converting here mouse position to the world space (you can do other way around). Debug.Log may give you some insight, how much do these positions differ.

Regarding constant length, that should be already accomplished by distance argument in your Raycast call.

Last thing, multiplying direction vector like this: mousePosition * 0.1f doesn't really do that much, since it's only to give direction, it isn't used to determince ray or debug ray length.

Related