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;
相关推荐
温宇飞7 分钟前
C++ 作用域和标识符查找规则详解
c++
随意0238 分钟前
STL 1 容器
开发语言·c++
cpp加油站1 小时前
拒绝切换IDE,10分钟让Trae编辑器化身C++神器,智能补全、编译调试一网打尽
c++·ai编程·trae
啊我不会诶1 小时前
篮球杯软件赛国赛C/C++ 大学 B 组补题
c语言·c++
l1t1 小时前
DeepSeek辅助实现的DuckDB copy to自定义函数
数据库·c++·人工智能
Bardb2 小时前
01__C++入门
c++·qt
weixin_457665394 小时前
C++11新标准
开发语言·c++
Thomas游戏开发4 小时前
Unity3D 自动化游戏框架设计
前端框架·unity3d·游戏开发
奔跑吧邓邓子4 小时前
解锁Vscode:C/C++环境配置超详细指南
c语言·c++·vscode·配置指南
oyishyi5 小时前
从零开始独立游戏开发学习笔记(七十八)--绘画/像素画学习笔记(十五)--V大预科3.0(五)-第三,四周理论
游戏·游戏开发