演示
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_VisualField : MonoBehaviour
{
public Transform player; // 玩家角色
public float viewAngle = 50; // 敌人的视野角度
public float distance = 100; // 索敌半径
public float moveSpeed = 10; // 移动速度
public float faceAngle = 5; // 面向角度, 当角度大于这个值时, 进行朝向调整
// Update is called once per frame
void Update()
{
Vector3 playerPos = player.position;
playerPos.y = transform.position.y;
float pDis = Vector3.Distance(playerPos, transform.position);
if (pDis <= distance) // 在索敌范围内
{
// 使用Vector3.Angle取得无符号角度,即是以当前物体的transform.forward方向为基准的左右两边各180度
float angle = Vector3.Angle(playerPos - transform.position, transform.forward);
if(angle <= viewAngle / 2) // 视野角度的一半, 左右各一半
{
if(faceAngle < angle) // 使敌人调整面向
{
Quaternion targetRotation = Quaternion.LookRotation(playerPos - transform.position);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, 1 * Time.deltaTime);
}
// 朝玩家角色前进
Rigidbody obj_rigidbody = GetComponent<Rigidbody>();
obj_rigidbody.MovePosition(transform.position + transform.forward * moveSpeed * Time.deltaTime);
}
}
}
}