简体   繁体   English

Unity Physics2D.Raycast遇到大型2D对撞机的麻烦

[英]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. 我有一个非常简单的Unity组件,用于检查鼠标屏幕位置是否在2D对撞机内。

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. 我将Image对象添加到在“屏幕空间:相机”中渲染的Canvas,并将Box Collider 2D组件添加到图像。

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. 上面的代码在鼠标指针位于Box Collider 2D内部但不在外部时记录“命中”,这就是我想要的。

However, this is only true if the box collider is less than 120 x 120 in size. 但是,仅当盒对撞机的尺寸小于120 x 120时,这才是正确的。 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. 如果是那个大小或更大,我开始在屏幕上的任何地方获取日志输出-Physics2D.Raycast在整个屏幕上返回内容。 The Physics2D.Raycast seems to think that the collider suddenly takes up the whole screen, which it doesn't, it's not even close. Physics2D.Raycast似乎认为对撞机突然占据了整个屏幕,但实际上并没有,甚至还没有关闭。 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. 将对撞机缩小到115 x 115可以解决此问题,但是正如您可以想象的那样,我不希望在某些对撞机尺寸上出现特殊行为。 The Image is size 100x100. 图片尺寸为100x100。 If I make the collider size 1x1 (barely visible), the Raycaster gives a hit on the entire 100x100 image. 如果我将对撞机的大小设置为1x1(几乎看不到),则Raycaster会在整个100x100的图像上命中目标。

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. 编辑:CircleCollider2D有相同的问题-如果半径超过100左右,我突然在整个屏幕上与它碰撞。

Physics2D.Raycast is meant to be used in 2D space. Physics2D.Raycast打算在2D空间中使用。 As I was using UI elements in 3D space, Physics2D.Raycast didn't work as expected, GetRayIntersection should be used instead. 当我在3D空间中使用UI元素时,Physics2D.Raycast无法按预期工作,因此应改用GetRayIntersection。 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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