Unity中LineRenderer视觉显示与自身Positions不匹配问题求助(附路径跟随实现代码)
Unity中LineRenderer视觉显示与自身Positions不匹配问题求助(附路径跟随实现代码)
大家好!我正在Unity里做一个物体沿预设路径移动的功能,目前遇到一个奇怪的问题:LineRenderer的视觉显示和它自身存储的Positions数据不匹配,具体可以看这张[Unity问题截图]。
我的实现流程是这样的:
- 先在
Circle.cs脚本里计算出路径的所有点(这里我做的是四分之一圆路径) - 把计算好的点存储到物体上的LineRenderer组件中
- 最后用
Path.cs脚本让目标物体沿着LineRenderer里的这些路径点移动
下面是我用到的两段代码:
Circle.cs(路径点计算脚本)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Circle : MonoBehaviour { public float radius = 3; 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); } }
Path.cs(物体路径跟随脚本)
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; } } } }
我已经尝试过调整LineRenderer的缩放参数,但还是没能解决视觉显示和Positions不匹配的问题,有没有朋友能帮我找找原因或者给出解决方案呀?
备注:内容来源于stack exchange,提问作者M van Etten
相关产品推荐
相关产品推荐

