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;
相关推荐
Java资深爱好者3 小时前
如何在std::map中查找元素
开发语言·c++
安步当歌6 小时前
【FFmpeg】av_write_trailer函数
c语言·c++·ffmpeg·视频编解码·video-codec
shuguang258007 小时前
C++ 函数高级——函数重载——基本语法
开发语言·c++·visualstudio
抽风侠7 小时前
C++左值右值
开发语言·c++
DogDaoDao7 小时前
LeetCode 算法:二叉树中的最大路径和 c++
c++·算法·leetcode·二叉树·二叉树路径
添砖JAVA的小墨8 小时前
C++ 如何解决回调地狱问题
c++
且行且知8 小时前
C++课程期末复习全集
开发语言·c++·算法
誰能久伴不乏8 小时前
Qt 绘图详解
开发语言·c++·qt
K-Liberty9 小时前
VTK- 面绘制&体绘制
c++·图像处理·数据可视化
我们的五年9 小时前
【算法:贪心】:贪心算法介绍+基础题(四个步骤);柠檬水找零(交换论证法)
c语言·数据结构·c++·算法·贪心算法