2D Raycasting from player to mouse position is innaccurate

I was trying to make a Raycast fire from my player to wherever my mouse was, and it worked. However, when I pointed the mouse horizontally, the raycast would fire a bit above the mouse position. Here is the code:

private void Start()
    {
        mainCam = GameObject.Find("Main Camera").GetComponent<Camera>();
        lr = gameObject.GetComponent<LineRenderer>();
        lr.enabled = false;
        lr.useWorldSpace = true;
    }

    private void Update()
    {

        Vector3 mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
        mousePos.z = 0;

        if (Input.GetMouseButton(0))
        {
            //Raycast and line to show the violence
            RaycastHit2D ray = Physics2D.Raycast(transform.position, mousePos);
            if (ray.collider != null)
            {
                hitZone.position = ray.point;
                lr.SetPosition(0, transform.position);
                lr.SetPosition(1, hitZone.position);
                print(ray.collider.gameObject.name);
                lr.enabled = true;
            }
            else
            {
                lr.enabled = false;
                print("hit nothing");
            }
        }
        else lr.enabled = false;

When I move the mouse upwards, the raycast points at it perfectly. Does anyone have an idea on why this is happening?

Raycast expects a position and a direction as the first two arguments.

You are passing in two positions instead:
RaycastHit2D ray = Physics2D.Raycast(transform.position, mousePos); It is going to interpret mousePos as a direction, but it’s a position. This will lead to incorrect behavior. Instead of mousePos, you need to pass in the direction from your player to the mouse position as the second parameter.

Try this:RaycastHit2D ray = Physics2D.Raycast(transform.position, mousePos - transform.position);

3 Likes

As above. If you want to check between two points then that’s a Line segment and not a ray so use Physics2D.LineCast. Has to be said though, best to check against the docs first before you post a question or even write code; it’ll save you lots of time.

4 Likes

This worked perfectly. My monkey brain thought that making it a position would just use it as a direction; obviously, that wouldn’t work in hind sight. Thank you!