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?