有时候我们需要判断某个物体是否在另一个物体的扇形范围内,可以参考一下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是大于,请自行查看余弦角度对照表。