如何在游戏对象移动时移动Line Renderer [英] How to move a Line Renderer as its game object moves
问题描述
我创建了一个空的游戏对象,并通过脚本向其中添加了Line Renderer组件.我以为,一旦我调整了游戏对象的位置,对于线切割器也将同样如此,但事实并非如此.
I created an empty game object and added a Line Renderer component to it through a script. I thought that once I adjust the position of the game object, it would do likewise for the line rendeder, but that is not the case.
我尝试了useWorldSpace = false
,但是它完全改变了位置,使以下点成为一条直线,尽管我能够将游戏对象移动到该直线上.
I tried useWorldSpace = false
but it totally changed the positions making the following points a straight line, though I was able to move the game object to to the line.
public Vector3 beginPos = new Vector3 (-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3 (1.0f, 1.0f, 0);
有没有一种方法可以将点转换为我更熟悉的输入(这样,像上述点那样的点就不会形成直线)?还是我应该以其他方式来解决问题?我愿意接受另一种方法.
Is there a way I can convert points to input what I am more familiar with (so that points like the above points don't create a straight line) or should I be approaching the problem in a different way? I am open to a different approach.
更新
我想我留下了一个导入细节.我将使用由线渲染器制作的线来创建形状.因此,我需要能够四处移动线条以移动形状,这样我就不必总是重新计算线条的起点和终点.
I think I left an import detail. I'll be using lines made with line renderer to create shapes. So I need to be able to be able to move the lines around to move the shapes so I don't have to always recalculate the start and end points for the lines.
推荐答案
您只需要对其应用偏移即可.在Start
函数中获取线条渲染器位置+ GameObject的当前位置.将该偏移量应用于Update
函数中的LineRender
.
You just need to apply an offset to it. Get the line renderer position + the current position of the GameObject in the Start
function. Apply that offset to the LineRender
in the Update
function.
public Vector3 beginPos = new Vector3(-1.0f, -1.0f, 0);
public Vector3 endPos = new Vector3(1.0f, 1.0f, 0);
Vector3 beginPosOffset;
Vector3 endPosOffset;
LineRenderer diagLine;
void Start()
{
diagLine = gameObject.AddComponent<LineRenderer>();
diagLine.material = new Material(Shader.Find("Sprites/Default"));
diagLine.startColor = diagLine.endColor = Color.green;
diagLine.startWidth = diagLine.endWidth = 0.15f;
diagLine.SetPosition(0, beginPos);
diagLine.SetPosition(1, endPos);
//Get offset
beginPosOffset = transform.position - beginPos;
endPosOffset = transform.position - endPos;
}
void Update()
{
//Calculate new postion with offset
Vector3 newBeginPos = transform.position + beginPosOffset;
Vector3 newEndPos = transform.position + endPosOffset;
//Apppy new position with offset
diagLine.SetPosition(0, newBeginPos);
diagLine.SetPosition(1, newEndPos);
}
这篇关于如何在游戏对象移动时移动Line Renderer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!