gpt4 book ai didi

unity3d - Raycast 获取 Plane 命中的局部坐标

转载 作者:行者123 更新时间:2023-12-04 01:21:43 30 4
gpt4 key购买 nike

我有一个比例为 (64,1,36) 且旋转为 (90,-180,0) 的平面,并且需要 2d 坐标格式的光线转换的局部坐标:

(0,0)-------(64,0)
| |
| |
| |
(0,36)------(64,36)

使用我当前的代码:

RaycastHit hit;
Vector3 coords = new Vector3();
if (Physics.Raycast(GazeOriginCombinedLocal, GazeDirectionCombined, out hit, Mathf.Infinity))
{
if (!hit.transform.Equals("Cube"))
{
Pointer.transform.position = hit.point; //Green cube for visualization of hit in worldspace
// coords = RectTransformUtility.ScreenPointToLocalPointInRectangle(Plane, hit.point, Camera.main, out coords);// no result at all
}


}

试试这个:

hit.transform.InverseTransformPoint(hit.point)

给我这个

(5,-5)---(-5,-5)
| |
| (0,0) |
| |
(5,5)----(-5,5)

有人知道如何获得所需的格式吗?

这就是我的飞机是主相机的 child 和我的层次结构的样子: enter image description here enter image description here enter image description here提前致谢

最佳答案

我想你可以使用 Transform.InverseTransformPoint哪个

Transforms position from world space to local space.

然后,由于这也受到比例的影响,它再次受到平面比例的影响,使用 Vector3.Scale .

所以你的坐标可能应该是这样的

coords = hit.transform.localScale / 2f +  Vector3.Scale(hit.transform.InverseTransformPoint(hit.point), hit.transform.localScale);

现在不能测试它,因为在智能手机上打字。你可能例如需要根据您的需要和平面的旋转方式等来反转 y/z 分量。但我希望这能给您一个想法

为了调试错误,您可能应该逐步打印出这些值

var scale = hit.transform.localScale; // 64, 1, 36
var halfScale = scale / 2f; // 32, 0.5, 18

var localHitPoint = hit.transform.InverseTransformPoint(hit.point);
Debug.Log($"{nameof(localHitPoint)}:{localHitPoint:0.000}");

所以我最初在这里期望的值是这样的

(-0.5, 0.5, 0)----(0.5, 0.5, 0)
| |
| (0, 0, 0) |
| |
(-0.5, -0.5, 0)---(0.5, -0.5, 0)

但是 正如您现在添加的那样:您的飞机是旋转的!

X 上的 90° 实际上使 Y 和 Z 交换了位置。因此,为了获得所需的 Y 坐标,您宁愿阅读 localHitPoint.z

然后 Y 上的 180° 基本上反转了 X 和 Z。

所以我现在希望这些值看起来像

(0.5, 0, -0.5)----(-0.5, 0, -0.5)
| |
| (0, 0, 0) |
| |
(0.5, 0, 0.5)---(-0.5, 0, 0.5)

这看起来与您描述的值非常相似。 虽然不确定为什么因子为 10 以及为什么不需要切换 Y 和 Z。

但是,由于您实际上希望 0,0 位于左上角,因此您只需要翻转 X 轴并使用 Z 而不是 Y,所以

fixedLocalHitPoint = new Vector2(-localHitPoint.x, localHitPoint.z);
Debug.Log($"{nameof(fixedLocalHitPoint)}:{fixedLocalHitPoint:0.000}");

现在应该给你这样的值

(-0.5, -0.5)----(0.5, -0.5)
| |
| (0, 0) |
| |
(-0.5, 0.5)----(0.5, 0.5)

你仍然需要再次扩大规模

var scaledHitPoint = Vector2.Scale(fixedLocalHitPoint, new Vector2 (scale.x, scale.z));
Debug.Log($"{nameof(scaledHitPoint)}:{scaledHitPoint:0.000}");

现在应该给出如下值

(-32, -18)----(32, -18)
| |
| (0, 0) |
| |
(-32, 18)-----(32, 18)

这就是为什么你需要添加中心点作为引用

coords =  new Vector2(halfScale.x, halfScale.z) + scaledHitPoint;
Debug.Log($"{nameof(coords)}:{coords:0.000}");

现在应该是

(0, 0)------(64, 0)
| |
| (32, 18) |
| |
(0, 36)-----(64, 36)

我希望这能让人们更清楚地了解这些“奇怪”值的来源。


由于您的相机按比例缩放 1,1,1 并且没有涉及任何其他内容,老实说,我很难找到 10 的因子会在何处偷偷进入计算。

关于unity3d - Raycast 获取 Plane 命中的局部坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62540444/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com