UE5 发射物目标追踪

UE5 发射物目标追踪

思路

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

实现:

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

//向目标旋转
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度(或者设定的角度)后,就不再旋转。或者避免发射速度和旋转角度达成那个关系。

//向目标旋转
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;

相关推荐

  1. UE5 发射目标追踪

    2024-06-18 18:20:02       5 阅读
  2. YOLOv8+bytetrack实现多目标追踪

    2024-06-18 18:20:02       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-18 18:20:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-18 18:20:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-18 18:20:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-18 18:20:02       20 阅读

热门阅读

  1. MYSQL

    MYSQL

    2024-06-18 18:20:02      5 阅读
  2. C#面:请解释C#接口的显式实现有什么意义

    2024-06-18 18:20:02       6 阅读
  3. 联合类型和交叉类型

    2024-06-18 18:20:02       6 阅读
  4. 每天一个项目管理概念之干系人

    2024-06-18 18:20:02       7 阅读
  5. linux常用指令

    2024-06-18 18:20:02       3 阅读
  6. 2024大数据面试题汇总(更新中。。。)

    2024-06-18 18:20:02       8 阅读
  7. mysql中社区版如何杀死锁

    2024-06-18 18:20:02       6 阅读
  8. TypeScript中的枚举

    2024-06-18 18:20:02       7 阅读
  9. Python网络安全项目开发实战,如何看清Web攻击

    2024-06-18 18:20:02       10 阅读
  10. Ubuntu 22.04 一键安装 Oracle 11GR2 单机

    2024-06-18 18:20:02       6 阅读
  11. Spring Boot框架的原理及应用详解(一)

    2024-06-18 18:20:02       7 阅读