unity3d - 在移动和旋转线条时获取线条渲染器的位置
问题描述
我有一条带有线渲染器的线。用户可以移动和旋转它。如何获取已移动或旋转的线渲染器的新位置?由于线渲染器的顶点坐标不变,只有线对象整体的位置和旋转发生变化。
图像底部的位置不会随着移动或旋转而改变。这些位置由 getpositions() 方法返回,这在我的情况下没有用。
解决方案
统一的LineRenderer采用点列表(存储为Vector3 s)并通过它们绘制一条线。它以两种方式之一完成此操作。
局部空间:(默认)所有点都相对于变换定位。因此,如果您的游戏对象移动或旋转,线条也会移动和旋转。
世界空间:(您需要选中使用世界空间复选框)该线将被渲染在世界中与列表中的位置完全匹配的固定位置。如果游戏对象移动或旋转,这条线将保持不变
所以你真正想知道的是 “我如何获得我线中一个局部空间点的世界空间位置?”
这个常见的用例由 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,这是一个非常新的统一版本,但是使用的逻辑和方法应该非常相似。
推荐阅读
- javascript - 我可以从 XAMPP 访问我的本地网络设备吗?
- c++ - std::vector 的擦除功能
- .htaccess - 如何友好地显示 seo 的 url?
- azure-devops - 如何使用 Azure DevOps REST API 覆盖列表变量?
- python-3.x - 使用 upper() 方法弹出字母
- java - 导入 com.zaxxer.hikari.HikariConfig,无法解析符号,IntelliJ
- python - 绘制轨道类型错误:需要浮点数
- python - 为什么我的程序输出错误的天数?
- python - 在谷歌 colab 中尝试 sqlite 时导致错误消息“多行字符串中的 EOF”的原因是什么?
- c# - 当我第一次通过单击链接启动网站时,它显示错误