Unity - LineRender(可视)不匹配LineRender的位置



我想让一个对象在Unity中遵循一个预先的路径。

  1. 首先我在Circle.cs
  2. 中计算路径然后我将这些点存储在LineRender组件中
  3. 我让一个对象跟随Path.cs
  4. 中的位置

问题:LineRender(可视)不匹配LineRender的位置。参见:Unity截图

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Path : MonoBehaviour
{
// The linerender path to follow
public LineRenderer path;
// The speed at which to follow the path
public float speed = 5.0f;
// The current position on the path
private int currentPosition = 0;
void Update()
{
// Get the current position and target position on the path
Vector3 currentWaypoint = path.GetPosition(currentPosition);
Vector3 targetWaypoint = path.GetPosition(currentPosition + 1);
// Move towards the target waypoint
transform.position = Vector3.MoveTowards(transform.position, targetWaypoint, speed * Time.deltaTime);
// If we have reached the target waypoint, move to the next one
if (transform.position == targetWaypoint)
{
currentPosition++;
// If we have reached the end of the path, start again from the beginning
if (currentPosition >= path.positionCount)
{
currentPosition = 0;
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Circle : MonoBehaviour
{
public float radius = 3;
// Start is called before the first frame update
private int numPoints = 100;
private Vector3[] positions;

void Start()
{
positions = new Vector3[numPoints];
float angleIncrement = (Mathf.PI / 2) / numPoints; // Quarter circle in radians
for (int i = 0; i < numPoints; i++)
{
float angle = angleIncrement * i;
float x = radius * Mathf.Cos(angle);
float y = radius * Mathf.Sin(angle);
positions[i] = new Vector3(x, 0, y);
}
this.GetComponent<LineRenderer>().positionCount = numPoints;
this.GetComponent<LineRenderer>().SetPositions(positions);
}
}

我尝试调整LineRender的大小。

默认情况下,LineRenderer组件的位置是基于世界空间坐标的。

因此,这里有两个修复选项:
  1. 将LineRenderer的useWorldSpace属性设置为false(在代码中或在检查器中)

  2. 在将点添加到LineRenderer

    之前,添加点的偏移量

最新更新