RectTransform rectTransform = YOUR_TARGET_RECT_TRANSFORM;
var corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
var camera = Camera.main;
for(var i = 0; i < corners.Length; i++)
{
corners[i] = camera.WorldToScreenPoint(corners[i]);
}
var position = YOUR_TARGET_Transform.position;
// assuming that scale is applied to the target so that it matches with the target dimensions
var size = YOUR_TARGET_Transform.lossyScale;
// assuming your target is by default flat on the XZ plane
// => transform.up points towards the sky by default
// if the target is actually rotated you need to adjust those
var x = YOUR_TARGET_Transform.right * size.x * 0.5f;
var z = YOUR_TARGET_Transform.forward * size.z * 0.5f;
var corners = new Vector3[4];
corners[0] = position - x - z;
corners[1] = position - x + z;
corners[2] = position + x + z;
corners[3] = position + x - z;
一个小小的演示
public class TEST : MonoBehaviour
{
public RectTransform[] images;
// Update is called once per frame
void Update()
{
var position = transform.position;
// assuming that scale is applied to the target so that it matches with the target dimensions
var size = transform.lossyScale;
// assuming your target is by default flat on the XZ plane
// => transform.up points towards the sky by default
// if the target is actually rotated you need to adjust those
var x = transform.right * size.x * 0.5f;
var z = transform.forward * size.z * 0.5f;
var corners = new Vector3[4];
corners[0] = position - x - z;
corners[1] = position - x + z;
corners[2] = position + x + z;
corners[3] = position + x - z;
for (var i = 0; i < 4; i++)
{
corners[i] = Camera.main.WorldToScreenPoint(corners[i]);
images[i].position = (Vector2)corners[i];
}
}
}
1条答案
按热度按时间z31licg01#
由于您提到
GetLocalCorners
时假设您有一个RectTransform
=〉,因此您将首先通过GetWorldCorners,然后将其传递给WorldToScreenPoint因此,例如
现在
corners
在像素屏幕空间中。如果目标实际上不是
RectTransform
,你需要先自己计算世界空间中的角。一个小小的演示