unity3d 如何使用Unity中的Vuforia ARCamera获得图像目标四个角的屏幕位置?

ijxebb2r  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(187)

如何在Vuforia中找到图像目标的四个角的屏幕位置以进行透视变换?
“GetLocalCorners”返回一个四个角的数组,表示矩形的角。但是我需要图像角。
我想获得黄色点的屏幕位置(像素)

z31licg0

z31licg01#

由于您提到GetLocalCorners时假设您有一个RectTransform =〉,因此您将首先通过GetWorldCorners,然后将其传递给WorldToScreenPoint
因此,例如

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]);
}

现在corners在像素屏幕空间中。
如果目标实际上不是RectTransform,你需要先自己计算世界空间中的角。

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];
        }
    }
}

相关问题