简体   繁体   中英

Unity Physics2D.Raycast having trouble with large 2D colliders

I have a very simple Unity component that checks if a mouse screen position is inside a 2D collider.

var screenRay = Camera.main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0.0f));
RaycastHit2D hit = Physics2D.Raycast(screenRay.origin, screenRay.direction);
if (hit)
{
    Debug.Log("hit something");
}

I add an Image object to a Canvas that is rendering in Screen Space: Camera, and a Box Collider 2D component to the image.

The code above logs "hit something" when the mouse pointer is inside the Box Collider 2D but not when outside, which is what I want.

However, this is only true if the box collider is less than 120 x 120 in size. If it is that size or larger, I start to get log output everywhere on the screen - Physics2D.Raycast returns something all over the screen. The Physics2D.Raycast seems to think that the collider suddenly takes up the whole screen, which it doesn't, it's not even close. Shrinking the collider to 115 x 115 solves the issue, but as you can imagine, I don't want special behaviour on some collider sizes. The Image is size 100x100. If I make the collider size 1x1 (barely visible), the Raycaster gives a hit on the entire 100x100 image.

The size of the image has no effect. Does anyone know why this magic size suddenly is larger than specified?

EDIT: I have the same problem with CircleCollider2D - if the radius goes above somewhere around 100, suddenly I collide with it all over the screen.

Physics2D.Raycast is meant to be used in 2D space. As I was using UI elements in 3D space, Physics2D.Raycast didn't work as expected, GetRayIntersection should be used instead. This code worked fine:

var screenRay = Camera.main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0.0f));
RaycastHit2D hit = Physics2D.GetRayIntersection(screenRay);
if (hit)
{
    Debug.Log("hit something");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM