I’m running this code to detect when player clicks on certain areas on the screen.
private void Update()
{
if(Input.GetMouseButtonDown(0))
{
var worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var hit = Physics2D.Raycast(worldPoint, Vector2.zero);
print(hit.collider == null ? "no object hit" : hit.collider.name);
}
}
The areas have an Image component and a PolygonColldier2D attached. However the code always prints “no bject hit” no matter where I click. What am I missing?
This is a misuse of raycast using it to detect if a point is overlapping a 2D collider. Not simply because using a degenerate direction vector of zero is silly but also because queries such as this only detect inside colliders when Physics2D.queriesStartInColliders is true (set in the physics settings).
You should use OverlapPoint instead. If this doesn’t work then you need to check the position you’re getting from the camera conversion and that it is indeed at the position of the collider. Not using Orthographic camera mode can cause it to be not where you expect for instance.
Also, an image component is UI and has no effect on physics so it’s irrelevant. Another thing to note is that the results RaycastHit2D has a bool operator so you can do “if (hit) { }”. 