项目02《游戏-12-开发》Unity3D

基于      项目02《游戏-11-开发》Unity3D      ,

任务:实现场景怪物自动巡航 ,

首先在场景中创建小球命名为路径点WayPoint0,

取消小球的碰撞器Collider,

再复制两个改名为WayPoint1 和 WayPoint2 ,

在WayPoint0路径点0右键创建空父物体命名为PathA路径A,

将其他路径点0-2(3个路径点)拖拽至PathA作为子物体,

创建脚本WayPoint.cs:

双击脚本WayPoint.cs修改代码:

using UnityEngine;
public class Waypoint : MonoBehaviour{
    public Transform[] waypointArray;
    public float speed = 0.1f;   
    public int currentIndex = 0;  
    void Start(){
        Transform path = GameObject.Find("PathA").transform;
        if (path != null){
            waypointArray = new Transform[path.childCount];
            for (int i = 0; i < waypointArray.Length; i++)
                waypointArray[i] = path.GetChild(i);
        }
        else
            Debug.LogError("查找路径点父物体失败,仔细检查父物体名字");
    }
    void Update(){
        Vector3 direction = waypointArray[currentIndex].position - transform.position;
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 1f);
        transform.Translate(Vector3.forward * speed);
        if (direction.sqrMagnitude < 1f){
            currentIndex++;
            if (currentIndex > waypointArray.Length - 1)
                currentIndex = 0;
        }
    }
}
将导航脚本挂载在敌人怪物上,并添加三个路径点框选。将PathA路径的三个路径点拖拽进框选注意路径顺序,

最后将路径点的材质取消,关闭路径点的场景显示,

运行即可实现怪物自动导航自动了,

End.

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-09 14:26:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-09 14:26:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-09 14:26:03       82 阅读
  4. Python语言-面向对象

    2024-02-09 14:26:03       91 阅读

热门阅读

  1. 高精度加法 取余 分类讨论 AcWing 791. 高精度加法

    2024-02-09 14:26:03       48 阅读
  2. 【LeetCode每日一题】1122. 数组的相对排序

    2024-02-09 14:26:03       54 阅读
  3. LeetCode639. Decode Ways II——动态规划

    2024-02-09 14:26:03       41 阅读
  4. C++ .h文件类的调用

    2024-02-09 14:26:03       51 阅读
  5. 机器学习原理到Python代码实现之PolynomialRegression

    2024-02-09 14:26:03       42 阅读
  6. List 差集

    2024-02-09 14:26:03       39 阅读
  7. 侵入式智能指针和非侵入式智能指针

    2024-02-09 14:26:03       44 阅读
  8. 动态规划C语言

    2024-02-09 14:26:03       38 阅读
  9. Jetpack Room使用

    2024-02-09 14:26:03       47 阅读