最近在使用Unity商城里的Corgi Engine2D进行BOSS行为制作时,我发现原先写的检测机制不太合理,只能检测到BOSS的前方是否有玩家,而无法达到分距离检测,即判断玩家在BOSS的远处还是近处。于是准备重写检测逻辑,同时也希望能做到检测玩家是否在BOSS身后这一事件。
注意:使用本代码需要Unity商城中的Corgi Engine为基础,但逻辑都相通。
刚开始准备用RayCast自带的距离检测进行判断,但思考过后发现只用距离无法判断角色是否在BOSS身后。于是另想了一个方法,就是一次性使用两个RayCast判断一个区域,光说不明白,直接上图:

大概就是用一长一短两个RayCast,通过(长的检测玩家 && 短的检测不到玩家)判断角色是否在区间内,进而判断并返回角色位置。
AIDecision检测脚本代码:
using MoreMountains.Tools;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace MoreMountains.CorgiEngine
{
/// <summary>
/// This Decision will return true if any object on its TargetLayer layermask enters its line of sight. It will also set the Brain's Target to that object. You can choose to have it in ray mode, in which case its line of sight will be an actual line (a raycast), or have it be wider (in which case it'll use a spherecast). You can also specify an offset for the ray's origin, and an obstacle layer mask that will block it.
/// </summary>
[AddComponentMenu("Corgi Engine/Character/AI/Decisions/AI Decision Detect Target Line IN STATE")]
// [RequireComponent(typeof(Character))]
public class AIDecisionDetectTargetLineINSTATE : AIDecision
{
/// the possible detection methods
public enum DetectMethods { Ray, WideRay }
/// the possible detection directions
public enum DetectionDirections { Front, Back}
/// the detection method
[Tooltip("the detection method (ray casts a single ray, wideray casts a boxcast")]
public DetectMethods DetectMethod = DetectMethods.Ray;
/// the detection direction
[Tooltip("the detection direction (front, back, or both)")]
public DetectionDirections DetectionDirection = DetectionDirections.Front;
/// the width of the ray to cast (if we're in WideRay mode only
[Tooltip("the width of the ray to cast (if we're in WideRay mode only")]
public float RayWidth = 1f;
/// the distance up to which we'll cast our rays
[Tooltip("the distance up to which we'll cast our rays")]
public float DetectionDistance = 10f;
public float DetectionDistanceClose = 8f;
/// the offset to apply to the ray(s)
[Tooltip("the offset to apply to the ray(s)")]
public Vector3 DetectionOriginOffset = new Vector3(0,0,0);
/// the layer(s) on which we want to search a target on
[Tooltip("the layer(s) on which we want to search a target on")]
public LayerMask TargetLayer = LayerManager.PlayerLayerMask;
// public LayerMask TargetLayerLeft = LayerManager.CharacterLeftLayerMask;
// public LayerMask TargetLayerRight = LayerManager.CharacterRightLayerM

最低0.47元/天 解锁文章
9217





