UE4判断是否在扇形中的官方代码(C++)

34 篇文章 2 订阅

有时候我们需要判断某个物体是否在另一个物体的扇形范围内,可以参考一下UE4源码中的代码。
源码在**“AIHelpers.h”**
命名空间是 FAISystem


	//----------------------------------------------------------------------//
	// CheckIsTargetInSightCone
	//                     F
	//                   *****  
	//              *             *
	//          *                     *
	//       *                           *
	//     *                               *
	//   *                                   * 
	//    \                                 /
	//     \                               /
	//      \                             /
	//       \             X             /
	//        \                         /
	//         \          ***          /
	//          \     *    N    *     /
	//           \ *               * /
	//            N                 N
	//            
	//           
	//           
	//           
	//
	// 
	//                     B 
	//
	// X = StartLocation
	// B = Backward offset
	// N = Near Clipping Radius (from the StartLocation adjusted by Backward offset)
	// F = Far Clipping Radius (from the StartLocation adjusted by Backward offset)
	//----------------------------------------------------------------------//
	bool CheckIsTargetInSightCone(const FVector& StartLocation, const FVector& ConeDirectionNormal, float PeripheralVisionAngleCos,
		float ConeDirectionBackwardOffset, float NearClippingRadiusSq, float const FarClippingRadiusSq, const FVector& TargetLocation)
	{
		const FVector BaseLocation = FMath::IsNearlyZero(ConeDirectionBackwardOffset) ? StartLocation : StartLocation - ConeDirectionNormal * ConeDirectionBackwardOffset;
		const FVector ActorToTarget = TargetLocation - BaseLocation;
		const float DistToTargetSq = ActorToTarget.SizeSquared();
		if (DistToTargetSq <= FarClippingRadiusSq && DistToTargetSq >= NearClippingRadiusSq)
		{
			const FVector DirectionToTarget = ActorToTarget.GetUnsafeNormal();
			return FVector::DotProduct(DirectionToTarget, ConeDirectionNormal) > PeripheralVisionAngleCos;
		}

		return false;
	}

如果判断TargetLocation是否在Actor的AngleDegrees的扇形范围内:

//角度
float AngleDegrees=45.0f;
//Actor位置指向目标位置的向量
const FVector ActorToTarget = TargetLocation - GetActorLocation();
//cos的弧度
float CosRadians = FMath::Cos(FMath::Clamp(FMath::DegreesToRadians(AngleDegrees), 0.f, PI));
//归一化后的方向向量点乘得到Cos(角度/弧度)
if(FVector::DotProduct(ActorToTarget.GetUnsafeNormal(), GetActorForwardVector())>CosRadians)
{
	在内部;
}
else{
	未在内部;
}

注:为什么FVector::DotProduct(ActorToTarget.GetUnsafeNormal(), GetActorForwardVector())>CosRadians是大于,请自行查看余弦角度对照表

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值