在unity中实现物体根据读取的坐标进行移动

这里写自定义目录标题

数据示例

-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;
    }
}

  • 3
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 25
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值