UE5 发射物目标追踪

UE5 发射物目标追踪

思路

求出需要旋转的角度,然后每帧旋转,再更新速度

实现:

求出发射物当前方向和目标方向的旋转后,插值求每帧的旋转。

cpp 复制代码
//向目标旋转
float Speed = MovementComponent->Velocity.Length();
//获取发射物坐标到目标几何中心的方向向量
FVector Origin, BoxExtent;
TraceTarget->GetActorBounds(false, Origin, BoxExtent);
FVector TargetVector = Origin - GetActorLocation();
TargetVector.Normalize();
//获取发射物速度到目标几何中心的方向向量的旋转四元数
FQuat RotationQuat = FQuat::FindBetweenVectors(MovementComponent->Velocity, TargetVector);
FQuat TargetRotationQuat = FQuat::Slerp(FQuat::Identity, RotationQuat, RotateSpeed * DeltaTime);
//更新速度
MovementComponent->Velocity = TargetRotationQuat.RotateVector(MovementComponent->Velocity).GetSafeNormal() * Speed;

但是这样写有个致命的缺点:每帧旋转的角度与需要旋转的角度正相关,角度越小旋转越小,角度越大旋转越大,我们不能接受

直接旋转固定角度

计算出需要的角度,然后每帧旋转固定角度。

发射物旋转我们需要注意的地方就是,在发射物的速度和旋转角度都很大且达到某一个平衡时,如果离目标足够近就可能导致变成绕着目标旋转。

我们可以选择设定当需要旋转的角度大于90度(或者设定的角度)后,就不再旋转。或者避免发射速度和旋转角度达成那个关系。

cpp 复制代码
//向目标旋转
float Speed = MovementComponent->Velocity.Length();
//获取发射物坐标到目标几何中心的方向向量
FVector Origin, BoxExtent;
TraceTarget->GetActorBounds(false, Origin, BoxExtent);
FVector TargetVector = Origin - GetActorLocation();
TargetVector.Normalize();
FQuat RotationQuat = FQuat::FindBetweenVectors(MovementComponent->Velocity, TargetVector);
float Angle = RotationQuat.GetAngle();
UE_LOG(LogTemp, Display, TEXT("Angle : %f, RotateAngle : %f"),FMath::RadiansToDegrees(Angle), FMath::RadiansToDegrees(RotateAngle));
if(Angle < FMath::DegreesToRadians(5))
{
	MovementComponent->Velocity = TargetVector.GetSafeNormal() * Speed;
	return;
} 
float RotationDirection = FMath::Sign(Angle);
//RotateAngle是类的成员
FQuat DeltaRotation = FQuat(RotationQuat.GetRotationAxis(), RotationDirection * RotateAngle * DeltaTime );
//更新速度
MovementComponent->Velocity = DeltaRotation.RotateVector(MovementComponent->Velocity).GetSafeNormal() * Speed;
相关推荐
SmalBox44 分钟前
【节点】[MetalReflectance节点]原理解析与实际应用
unity3d·游戏开发·图形学
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
SmalBox1 天前
【节点】[FresnelEquation节点]原理解析与实际应用
unity3d·游戏开发·图形学
不想写代码的星星1 天前
虚函数表:C++ 多态背后的那个男人
c++
xiezhr1 天前
米哈游36岁程序员被曝复工当晚猝死出租屋内
游戏·程序员·游戏开发
SmalBox2 天前
【节点】[DielectricSpecular节点]原理解析与实际应用
unity3d·游戏开发·图形学
开维游戏引擎3 天前
开维游戏引擎实例:飞机大战
游戏开发
端平入洛3 天前
delete又未完全delete
c++
SmalBox3 天前
【节点】[LinearBlendSkinning节点]原理解析与实际应用
unity3d·游戏开发·图形学
SmalBox4 天前
【节点】[ComputeDeformation节点]原理解析与实际应用
unity3d·游戏开发·图形学