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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

飞翔的小鸟——   2021-09-12 我要评论
想了解Unity实现物体运动轨迹的绘制的相关内容吗,飞翔的小鸟——在本文为您仔细讲解Unity物体运动轨迹的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Unity物体运动轨迹,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拖进去,如下图:

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们