这篇文章主要为大家详细介绍了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拖进去,如下图:
⑥ 运行场景,可以看到如下效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:Unity实现物体运动轨迹的绘制


基础教程推荐
猜你喜欢
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中的Linq to JSON操作详解 2023-06-08
- C# 解析XML和反序列化的示例 2023-04-14
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#中 Json 序列化去掉null值的方法 2022-11-18
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16