Unity实现物体运动轨迹的绘制

 更新时间:2021年09月12日 17:17:17   作者:飞翔的小鸟——  
这篇文章主要为大家详细介绍了Unity实现物体运动轨迹的绘制,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了unity物体运动轨迹绘制的具体代码,供大家参考,具体内容如下

① create empty,命名为LineRender

② 在Assects中新建材质,选择Shader为Sprites/Default,并设置轨迹颜色,如下图:

③ 选择①中创建的object,添加Line Render属性,然后将②中新建的材质赋给该object,如下图:

展开Line Render,拖动Width可设置轨迹宽度

④ 创建c#脚本,拖至运动物体上,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class draw_orbit : MonoBehaviour
{
    // 绘制轨迹组件
    public LineRenderer line;
    public List<Vector3> points;
    // 读取本地txt文件位置信息,改变物体位置
    string[] text_buf;
    int i = 0;
    // Start is called before the first frame update
    void Start()
    {
     // 物体位置控制方法根据自己需求来,我这里是从txt文件读取位置信息然后更新
        TextAsset ta = Resources.Load("satellite_orbit") as TextAsset;
        string text = ta.text;
        text_buf = text.Split('\n');
    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            if (i < text_buf.Length)
            {
                // 读取坐标信息
                string[] line = text_buf[i].Split(',');
                float x = Convert.ToSingle(line[0])/1000;
                float y = Convert.ToSingle(line[1])/1000;
                float z = Convert.ToSingle(line[2])/1000;
                // 更新物体位置
                transform.position = new Vector3(x, y, z);
                // 绘制轨迹
                AddPoints();
            }
            i++;
        }
        catch(Exception ex) {
            Debug.Log(ex.Message);
        }
        
    }

    // 绘制轨迹方法
    public void AddPoints()
    {
        Vector3 pt = transform.position;
        if (points.Count > 0 && (pt - lastPoint).magnitude < 0.1f)
            return;
        if (pt != new Vector3(0, 0, 0))
            points.Add(pt);

        line.positionCount = points.Count;
        if (points.Count > 0)
            line.SetPosition(points.Count - 1, lastPoint);
    }
    public Vector3 lastPoint
    {
        get
        {
            if (points == null)
                return Vector3.zero;
            return (points[points.Count - 1]);
        }
    }
}

⑤ 选中运动物体,可以看到其Script组件中出现Line Render属性,将①中的object拖进去,如下图:

⑥ 运行场景,可以看到如下效果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

最新评论