数据示例
-30 -55
-30 -57.5
-30 -60
-30 -60
-27.5 -60
-25 -60
-22.5 -60
-20 -60
-17.5 -60
-15 -60
-12.5 -60
-10 -60
-10 -60
-10 -61.5
-10 -63
-10 -64.5
-10 -66
-10 -67.5
-10 -69
详细代码
using System.Collections;
using UnityEngine;
using System.IO;
using System.Text;
using System;
public class WentToAimPoint : MonoBehaviour
{
ArrayList al = new ArrayList(); //创建动态数组,存取数据点
public float moveSpeed = 5.0f;
public GameObject person7;
private string path = @"D:\Software\UnityWorkSpace\DataFile\WZheng\print2.txt";
void Start()
{
person7=GameObject.FindWithTag("targetPerson"); //获取物体
ReadToArrayList();
}
int num = 0; //控制Update次数,也即读取集合元素的个数。
void FixedUpdate()
{
if (num > al.Count - 6) //防止ArrayList下标越界(不能放在Move()方法里,会报错--->原因我也不知道!)
{
return; //虽然程序返回了,但是使用的是FixedUpdate,所以程序还是在运行着
}
Move();
}
//从Text文本文件中读取数据到数组中
public void ReadToArrayList()
{
string txtPath = path;
StreamReader sr = new StreamReader(txtPath, Encoding.Default);
string line; //控制读取行
while ((line = sr.ReadLine()) != null)
{
string[] str = line.Split(' ');
for (int i = 0; i < str.Length; i++)
{
al.Add(str[i]);
}
}
}
public void Move() //物体移动方法
{
double prePointX, prePointZ;
double nextPointX, nextPointZ;
// 1.从ArrayList中获取数据并赋值
prePointX = Convert.ToDouble(al[num].ToString());
prePointZ = Convert.ToDouble(al[num + 1].ToString());
Vector3 v0 = new Vector3((float)prePointX, (float)1.564f, (float)prePointZ);
nextPointX = Convert.ToDouble(al[num + 2].ToString());
nextPointZ = Convert.ToDouble(al[num + 3].ToString());
Vector3 v1 = new Vector3((float)nextPointX, (float)1.564f, (float)nextPointZ);
print(v1-v0);
person7.transform.Translate((v1 - v0).normalized * Time.fixedDeltaTime * moveSpeed * 8);
num += 2;
}
}