找出对象的盒子实际的4个按比例缩放到屏幕/相机尺寸的边缘(Unity 2D) [英] Find out an object's box actual 4 edges scaled to the screen/camera size (Unity 2D)

查看:258
本文介绍了找出对象的盒子实际的4个按比例缩放到屏幕/相机尺寸的边缘(Unity 2D)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数来确定2D对象是否完全在另一个对象内部. 我这样做是通过获取对象的位置,然后获取此位置及其大小,计算对象的边缘位置,然后使用Camera.main.pixelRect.Contains进行检查.这是我当前的代码:

I'm writing a function to figure out if a 2D object is completely inside another. I'm doing this by getting the object's position, then with this position and it's size, calculating the object's edges position, then doing a check with Camera.main.pixelRect.Contains. This is my current code:

 // get the center of the object
 Vector2 pos = Camera.main.WorldToScreenPoint(card.transform.position);

 // get the bounding box
 var rect = image.transform.rect;

 var topLeft = new Vector2(pos.x - (rect.width / 2), pos.y - (rect.height / 2);


return Camera.main.pixelRect.Contains(topLeft);

我的问题是,Unity刚开始使用时,测量值不匹配.当对象按屏幕尺寸缩放时,我很困惑,我将获得图像的实际宽度,并且计算错误.

My problem is, being new to Unity, the measurements do not match. I'm confused on when the object is scaled with the screen size, I will get the actual width of the image and it calculates wrong.

我还测试了如何通过以下方式进行矫正:

I also tested getting rect with:

rect = GetComponent<RectTransform>().rect;

有人可以帮助我完成这项工作吗?

Can someone help me out how to make this work?

Ps:如果有更好的方法来检查2D对象何时完全位于另一个对象中,我也将接受.

Ps: if there is a better way of checking when a 2D object is completely inside another, I would also accept that.

推荐答案

正如Draco18s指出的那样,您将pos转换为屏幕空间,而不是rect.

As Draco18s pointed out, you convert pos to screenspace but not rect.

如果您查看WorldToScreenPoint()的unity API文档 它说

If you look at unity's API docs for WorldToScreenPoint() it says that it

将位置从世界空间转换为屏幕空间.屏幕空间为 以像素为单位.

Transforms position from world space into screen space. Screenspace is defined in pixels.

transform.position返回

变换在世界空间中的位置.

The position of the transform in world space.

您遇到的问题是将屏幕空间(以像素为单位)和世界空间结合在一起,这是完全不同的.

What you have is a problem of combining screenspace, measured in pixels, and world space, which is totally different.

由于您使用的是pixelRect,因此建议您更改var rect = image.transform.rect; 成为var rect = Camera.main.WorldToScreenPoint(image.transform.position);

Because you are using pixelRect, I would recommend changing var rect = image.transform.rect; to be var rect = Camera.main.WorldToScreenPoint(image.transform.position);

然后,您当然也必须以类似的方式检查其他角,如果所有4个角都返回true,则该对象位于另一个内部.

You will then of course have to also check the other corners in a similar way, and if all 4 corners return true then the the object is inside the other.

这篇关于找出对象的盒子实际的4个按比例缩放到屏幕/相机尺寸的边缘(Unity 2D)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆