unity3d 如何在Unity C#中将动画转换为线渲染器

qpgpyjmq  于 2022-12-13  发布在  C#
关注(0)|答案(1)|浏览(183)

有没有办法给这个线渲染器添加动画?我的意思是我想画一条从点1到点3的线,这条线应该像进度条一样移动。如何在下面的脚本中做到这一点

public class DrawLineRenderer : MonoBehaviour
    {
        public Transform Point1;
        public Transform Point2;
        public Transform Point3;
        public LineRenderer linerenderer;
        public float vertexCount = 12;
        public float Point2Ypositio = 2;
        // Start is called before the first frame update
        void Start()
        {
            linerenderer.SetWidth(10, 10);
        }

    // Update is called once per frame
    void Update()
    {
       
    }
    public void buttonPress()
    {
         Point2.transform.position = new Vector3((Point1.transform.position.x + Point3.transform.position.x)/2, Point2Ypositio, (Point1.transform.position.z + Point3.transform.position.z) /2);
        var pointList = new List<Vector3>();

        for(float ratio = 0;ratio<=1;ratio+= 1/vertexCount)
        {
            var tangent1 = Vector3.Lerp(Point1.position, Point2.position, ratio);
            var tangent2 = Vector3.Lerp(Point2.position, Point3.position, ratio);
            var curve = Vector3.Lerp(tangent1, tangent2, ratio);

            pointList.Add(curve);
        }

        linerenderer.positionCount = pointList.Count;
        linerenderer.SetPositions(pointList.ToArray());
    }

}

omhiaaxx

omhiaaxx1#

若要使用线性插值设置线渲染器的动画,可以使用Lerp()方法在线的点之间进行插值。
下面是一个示例,说明如何实现这一点:

#region Serialized Fields

[SerializeField] private LineRenderer lineRenderer;
[SerializeField] private Transform[] positions;
[SerializeField] [Range(1, 4)] private float animationSpeed = 2f;

#endregion

private int _currentPosition;
private float _interpolation;
private bool _isAnimating;

#region Event Functions

private void Update()
{
    if (!_isAnimating) return;

    var startPoint = positions[_currentPosition].position;
    var endPoint = positions[_currentPosition + 1].position;
    var currentPoint = Vector3.Lerp(startPoint, endPoint, _interpolation);

    lineRenderer.positionCount = _currentPosition + 2;
    lineRenderer.SetPosition(_currentPosition, startPoint);
    lineRenderer.SetPosition(_currentPosition + 1, currentPoint);

    // Increment interpolation value over time
    _interpolation += Time.deltaTime * animationSpeed;

    // If the end of the line has been reached, move to the next position
    if (_interpolation >= 1.0f)
    {
        _interpolation = 0.0f;
        _currentPosition++;

        // Stop animating if all positions have been visited
        if (_currentPosition >= positions.Length - 1)
            _isAnimating = false;
    }
}

#endregion

/// <summary>
///     Resets then starts the animation of the line renderer
/// </summary>
public void ButtonPress()
{
    _isAnimating = true;
    _interpolation = 0;
    _currentPosition = 0;
}

此脚本使用Update()循环中的Lerp()设置线条渲染器的位置,并在调用ButtonPress()函数时通过将_isAnimating标志设置为true来启动动画。这将使线条在每次按下按钮时从起点到终点进行动画显示。

相关问题