实现旋转平台

在之前的文章中,我们已经实现了移动平台(在 location 属性上变化)。在这篇文章中,我们继续实现旋转平台(在 rotation 属性上变换)。

如代码清单 1 所示,我们首先增加一个编辑器属性,指定旋转的速度。并定义 HandleRotation 函数处理物体旋转。

FRotator 是一种使用欧拉角表示旋转的方式。分别描述物体绕 X 轴、Y 轴和 Z 轴的旋转。

代码清单 1 MovingPlatform.h
  1. UCLASS()
  2. class OBSTACLE_API AMovingPlatform : public AActor
  3. {
  4. public:
  5.     // Euler angle rotation speed
  6.     UPROPERTY(EditAnywhere, Category = "Rotation")
  7.     FRotator RotationVelocity;
  8.  
  9. private:
  10.     void HandleRotation(float DeltaTime);
  11. };

HandleRotation 的实现很简单,如代码清单 2 所示,我们直接调用 AddActorLocalRotation() 函数来增量旋转物体。

GetActorRotation() 加上增量的方法,可能会遇到万向节死锁的问题。

代码清单 2 MovingPlatform.cpp
  1. void AMovingPlatform::HandleRotation(float DeltaTime)
  2. {
  3.     FRotator RotationIncrement = RotationVelocity * DeltaTime;
  4.     AddActorLocalRotation(RotationIncrement);
  5. }

在 C++ 中实现好旋转功能后,我们基于这个 C++ 类,创建一个新的蓝图类。我把它命名为 BP_RotatingPlatform,并添加了一个圆盘 Mesh。

我们把 BP_RotatingPlatform 放置在场景中,设置好属性,形成新的障碍物。最终的效果如下方视频所示。