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).