unity3D-模拟物体巡游-绕位置点循环移动+自身旋转

在这里插入图片描述
这里用空物体代表位置点。
target.cs脚本,挂在target问题上。

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

public class Target : MonoBehaviour
{
    private Transform[] positions;//Transform[] 存放位置点transform

    public float speed = 10;//初始化移动的速度为10

    private int index = 0;//定义数组下标
    // Start is called before the first frame update
    void Start()
    {
        positions = WayPoints.positions;//拿到设置的位置点
    }

    // Update is called once per frame
    void Update()
    {
        Move();
        //transform.rotation(new Vector3(0,1,0));
        transform.Rotate(new Vector3(1, 1, 1)); 
    }

    void Move()
    {
        if (index > positions.Length - 1) index=0;//当跑到最后一个点的时候报数组越界异常
        transform.Translate((positions[index].position - transform.position).normalized * Time.deltaTime * speed);//朝位置点移动
        //认为物体的位置和位置点的位置的距离小于0.2的时候,到达位置点,让index++
        if (Vector3.Distance(positions[index].position, transform.position) < 0.2)
        {
            index++;
        }
    }
}

wayPoints.cs

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

public class WayPoints : MonoBehaviour
{
    //此脚本挂在waypoints 
    public static Transform[] positions;//获取所有位置点的transform组件,组成一个数组
    private void Awake()
    {
        positions = new Transform[transform.childCount];//创建数组
        for (int i = 0; i < positions.Length; i++)//初始化数组
        {
            positions[i] = transform.GetChild(i);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
    }
}

效果:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值