首页 > 解决方案 > 在移动和旋转线条时获取线条渲染器的位置

问题描述

我有一条带有线渲染器的线。用户可以移动和旋转它。如何获取已移动或旋转的线渲染器的新位置?由于线渲染器的顶点坐标不变,只有线对象整体的位置和旋转发生变化。

线对象的屏幕截图

图像底部的位置不会随着移动或旋转而改变。这些位置由 getpositions() 方法返回,这在我的情况下没有用。

标签: unity3dgeometry

解决方案


统一的LineRenderer采用点列表(存储为Vector3 s)并通过它们绘制一条线。它以两种方式之一完成此操作。

  1. 局部空间:(默认)所有点都相对于变换定位。因此,如果您的游戏对象移动或旋转,线条也会移动和旋转。

  2. 世界空间:(您需要选中使用世界空间复选框)该线将被渲染在世界中与列表中的位置完全匹配的固定位置。如果游戏对象移动或旋转,这条线将保持不变

所以你真正想知道的是 “我如何获得我线中一个局部空间点的世界空间位置?”

这个常见的用例由 gameObjects 变换上的方法解决

变换.变换点

它需要一个局部空间点(这是数据在默认情况下在线渲染器中存储的方式)并将其转换为世界空间。

一个例子:

using UnityEngine;
using System.Collections;

public class LineRendererToWorldSpace : MonoBehaviour
{
    private LineRenderer lr;

    void Start()
    {
        lr = GetComponent<LineRenderer>();

        // Set some positions in the line renderer which are interpreted as local space
        // These are what you would see in the inspector in Unity's UI
        Vector3[] positions = new Vector3[3];
        positions[0] = new Vector3(-2.0f, -2.0f, 0.0f);
        positions[1] = new Vector3(0.0f, 2.0f, 0.0f);
        positions[2] = new Vector3(2.0f, -2.0f, 0.0f);
        lr.positionCount = positions.Length;
        lr.SetPositions(positions);
    }

    Vector3[] GetLinePointsInWorldSpace()
    {
        Vector3[] positions;
        //Get the positions which are shown in the inspector 
        var numberOfPositions = lr.GetPositions(positions);
        //Iterate through all points, and transform them to world space
        for(var i = 0; i < numberOfPositions; i += 1)
        {
            positions[i] = transform.TransformPoint(positions[i]);
        }

        //the points returned are in world space
        return positions;
    }
}

此代码仅用于演示目的,因为我不确定用例。另外,我的链接是 2018.2,这是一个非常新的统一版本,但是使用的逻辑和方法应该非常相似。


推荐阅读