1、首先创建一个平面和两个小球,个其中一个小球命名为Player,另一个命名为enemy,并给他们赋予不同的颜色以示区别,如下图
2、编写脚本使Player移动
创建一个脚本命名为move,并赋予小球,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class move : MonoBehaviour
{
public float speed = 6.0f;
public float gravity = -9.8f;
private CharacterController _charController;
// Start is called before the first frame update
void Start()
{
_charController = GetComponent<CharacterController>();//使用附加到相同对象上的其他组件
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxis("Horizontal") * speed;
float z = Input.GetAxis("Vertical") * speed;
Vector3 movement = new Vector3(x, 0, z);
movement = Vector3.ClampMagnitude(movement, speed);//使对角移动的速度和沿轴移动的速度一样
movement.y = gravity;
movement *= Time.deltaTime;
movement = transform.TransformDirection(movement);//本地坐标变为全局坐标
_charController.Move(movement);//character通过movement向量移动
}
}
注意:要给小球添加一个characterController,小球才能移动
3、敌人追逐玩家
首先进行网格烘焙,Windows->AI->navigation,然后选中平面,设置参数如下,选择bake,点击右下角bake进行烘焙
创建一个正方体作为障碍物,把正方体放在合适的位置
继续进行烘焙,选择cube,设置nagivation的参数如下,选择bake,点击右下角的bake进行烘焙
烘焙完成后效果如下,其中蓝色区域是可行走的区域,白色区域是不可行走的区域
给敌人添加一个导航网格,选中敌人,选择Component
编写一个脚本命名为enemy,并把脚本赋予enemy,代码如下:
using System.Collections;
using System.Drawing;
using UnityEngine;
using UnityEngine.AI;
public class enemy : MonoBehaviour
{
NavMeshAgent pathfinder;
Transform target;
void Start()
{
pathfinder = GetComponent<NavMeshAgent>();
target = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
pathfinder.SetDestination(target.position);
}
}
点击运行,敌人就能追着玩家跑啦!