How Can I Make A Ray Cast From The Bottom of My Player

Viewed 31

I'm a beginner game developer and I'm making a top down 2D game. The player's collider is on the bottom half of his body, kind of like Stardew Valley. In order to detect when the player hits a tree, I cast a ray from the player to the mouse. The problem is that the ray casts from the middle of the player, which means when you're north of the tree, you can't hit it, and it just acts really weird. I need a way to cast the ray from the player's feet. Here's the code I have:

void Update()
    {
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector3 offset = new Vector3(0, -0.35f, 0);

        if (Input.GetMouseButtonDown(0))
        {
            Debug.DrawRay(playerRb.transform.position, mousePosition - playerRb.transform.position, Color.red);

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

            var treeScript = hit.collider.GetComponent<TreeScript>();

            if (hit.collider != null)
            {
                if (hit.collider.tag == "Tree")
                {
                    treeScript.Break();
                    Debug.Log("Hit Tree");
                }
            }
        }
    }

I tried adding the "offset" variable to my playerRb position, and the game runs, but for whatever reason, the raycast doesn't work anymore. The offset works fine on DrawRay.

1 Answers

Try using Physics2D.Linecast instead. Other people have been having problems with this too, and they used linecast instead and it worked.

Try something like

RaycastHit2D hit = Physics2D.Linecast(transform.position + offset, mousePosition);
Related