首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从渲染纹理中获取三维世界空间位置

如何从渲染纹理中获取三维世界空间位置
EN

Stack Overflow用户
提问于 2016-04-26 07:33:31
回答 1查看 4.7K关注 0票数 8

我正在使用Render Texture制作一个侧图,它运行得很好,并且我已经通过这些步骤完成了它。

  1. 一个主要的摄像机渲染场景。
  2. NGUI相机渲染GUI。
  3. 该GUI包含渲染纹理(minimap),它使用GUI摄像机在纹理上呈现场景。

,但,现在我想进一步改进地图,希望它变得棘手。我想从渲染纹理点击点的世界空间位置。有任何方法可以从渲染纹理的特定点击点获得世界空间位置吗?

如果我点击渲染纹理的某个地方,我如何才能在三维世界的空间点。

例如:我在渲染纹理上单击了一个汽车对象。现在,我怎样才能在3D世界中高亮显示或者得到它呢?如何将2D渲染纹理点击位置转换为世界空间位置!

EN

回答 1

Stack Overflow用户

发布于 2016-04-27 14:27:06

这假设了一些事情。

首先,我使用EventSystems来获得鼠标点击。这不是必需的,它可以很容易地更改(虽然^^)。要正确设置它,您需要场景中的一个EventSystem (如果您有一个UI,您可能已经有一个了)。

其次,您需要将一个PhysicsRaycaster组件附加到您的主摄像机(播放机看穿的摄像机)。

最后,在包含渲染纹理渲染器的GameObject上(我使用了一个简单的四角体),您可以应用下面的脚本并分配相应的摄像机。

代码语言:javascript
复制
using UnityEngine;
using UnityEngine.EventSystems;

//i chose box collider because its cheap
[RequireComponent(typeof(BoxCollider))]
public class RenderTextureRaycaster : MonoBehaviour, IPointerDownHandler {

    //assign in inspector
    public Camera portalExit;

    BoxCollider portal;
    Vector3 portalExitSize;

    void Start() {
        portal = GetComponent<BoxCollider>();
        //this is the target camera resolution, idk if there is another way to get it.
        portalExitSize = new Vector3(portalExit.targetTexture.width, portalExit.targetTexture.height, 0);
    }

    public void OnPointerDown(PointerEventData eventData) {
        //the click in world space
        Vector3 worldClick = eventData.pointerCurrentRaycast.worldPosition;
        //transformed into local space
        Vector3 localClick = transform.InverseTransformPoint(worldClick);
        //since the origin of the collider is in its center, we need to offset it by half its size to get it realtive to bottom left
        Vector3 textureClick = localClick + portal.size / 2;
        //now we scale it up by the actual texture size which equals to the "camera resoution"
        Vector3 rayOriginInCameraSpace = Vector3.Scale(textureClick, portalExitSize);

        //with this knowledge we can creata a ray.
        Ray portaledRay = portalExit.ScreenPointToRay(rayOriginInCameraSpace );
        RaycastHit raycastHit;

        //and cast it.
        if (Physics.Raycast(portaledRay, out raycastHit)) {
            Debug.DrawLine(portaledRay.origin, raycastHit.point, Color.blue, 4);
        }
        else {
            Debug.DrawRay(portaledRay.origin, portaledRay.direction * 100, Color.red, 4);
        }
    }
}

编辑:上面可能有点冗长,如果您喜欢一个行,您可以轻松地减少它,这只是为了说明它是如何工作的。此外,请只考虑这是一个概念的证明,它没有经过彻底的测试。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36858223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档