
x,y就是rect类的根坐标,有了它我们就能确定我们就能确定矩形的位置。
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Rect r=new Rect(0,0,200,200);
print(r.Contains(Input.mousePosition));
}
}
这时候我们点击我们屏幕的左下角,发现返回true,完全可以点击到。
对!其实就是这么简单,不要被官网的说明误导。它就是根坐标在左下角,根据width与height向右和向上画出来的一个矩形,但是还稍稍有点不太一样。
在UGUI中,transform.rect你得到的相关属性或许很会奇怪。接下来的例子我们都以transform.rect得到的值来讲解。
我们在界面中添加一个Image,他的锚点与pivot值都不变,具体如下图:
这时候他的长宽都是知道的。我们输出trans.rect.x与trans.rect.y会是什么呢?
结果是(-50,-50),rect.size就是对x与y的包装。
因为rect的根是基于pivot的值来算的,把pivot的位置作为整个图形坐标的原点(0,0)。那么trans.rect的x与y因而所以就在第三象限为负值。
那么trans.rect.x与y的算法就是x=-widthpivot.x 和 y=-heightpivot.y。
下面用一张图来帮助理解。
print("trans's rect x and y"+trans.rect.x+" "+trans.rect.y);
print("caculate rect x and y"+-trans.rect.width*trans.pivot.x+" "+-trans.rect.height*trans.pivot.y);
//trans.rect.position就是 x和y的封装
结果输出:
举一反三
那么如果pivot改为(0.5,1),trans.rect的xy各是多少呢?还是一样的公式,此时整个坐标的原点到了图形最上面那一条边的中间了,trans.rect的xy为(-50,-100)。
总结:UGUI中rect的根坐标是基于pivot的位置来计算的。其他场景下的rect可以认为pivot为(0,0),那么rect的根坐标也就自然为(0,0)。
rect.min和rect.maxrect.min也就是(rect.x,rect.y),表示左下角坐标也就是根坐标
rect.max就是(width+rect.x,height+rect.y),表示右上角坐标
同时rect.min=(rect.xMin,rect.yMin) rect.max(rect.xMax,rect.yMax)
(以下例子pivot为(0.5,0.5)):
print("trans's rect min and max"+trans.rect.min+" "+trans.rect.max);
print("caculate rect min and max"+new Vector2(trans.rect.x,trans.rect.y)+" "+new Vector2(trans.rect.width+trans.rect.x,trans.rect.height+trans.rect.y));
举一反三
如果这是pivot为(0,1)呢?
通过上面的公式求的min(0,-100)max(100,0)