Hello everyone, im trying to make a simple farming game in 2D. But somethings not working.
When I click on a tile and I check the debug.drawray the ray goes a different direction then im pointing with my mouse. How do i fix this because it almost always says (when im clicking on the left side of my player, on the right side it’s almost always working) that the tile is to far away while im almost standing on it.
I hope someone can help me!
void Click()
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y)); ;
mousePos = new Vector3(mousePos.x, mousePos.y, 0);
RaycastHit2D hit = Physics2D.Raycast(mousePos, Vector2.zero, 3f);
Debug.DrawRay(this.gameObject.transform.position, mousePos, Color.red, 3);
if (hit.collider != null)
{
Debug.Log("Clicked on " + hit.collider.name);
if (hit.collider.CompareTag("Tilemap"))
{
Vector3Int cellPosition = tilemap.WorldToCell(mousePos);
TryChangeTile(cellPosition);
}
else if (hit.collider.CompareTag("Enemy"))
{
float distanceToPlayer = Vector3.Distance(transform.position, hit.collider.transform.position);
Debug.Log("Distance to Player: " + distanceToPlayer);
if (distanceToPlayer <= allowedRadius)
{
hit.collider.gameObject.GetComponent<Enemy>().health -= 2;
}
}
}
else
{
Debug.Log("No object hit.");
}
}