这是一个使用 Unity 引擎的 C# 脚本,用于控制怪物的移动。

首先,脚本引入了一些命名空间,包括 System.Collections、System.Collections.Generic、UnityEngine 和 UnityEngine.AI。

然后,定义了一些变量:

  • Transform target:要追踪的目标点,通常是玩家角色。
  • float moveSpeed:移动速度。

接下来,定义了一个私有变量:

  • NavMeshAgent navMeshAgent:导航代理组件。

在 Start() 函数中,脚本获取了挂载脚本的游戏对象上的 NavMeshAgent 组件,并将其速度设置为 moveSpeed。

在 Update() 函数中,如果目标点不为空,就调用 navMeshAgent 的 SetDestination() 函数,将目标点设置为怪物的移动目的地。

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

public class MonsterMovement : MonoBehaviour {
    public Transform target; // 要追踪的目标点,通常是玩家角色
    public float moveSpeed = 3f; // 移动速度

    private NavMeshAgent navMeshAgent; // 导航代理组件

    private void Start() {
        navMeshAgent = GetComponent<NavMeshAgent>();
        navMeshAgent.speed = moveSpeed;
    }

    private void Update() {
        if (target != null) {
            navMeshAgent.SetDestination(target.position);
        }
    }
}
Unity C# 怪物移动脚本:使用 NavMeshAgent 实现追踪

原文地址: https://www.cveoy.top/t/topic/qEaD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录