五、使用FRotationMatrix 使一个对象转向另一个对象
FRotationMatrix提供了一系列::Make* 矩阵结构。 它们易于使用,而且对于让一个物体面对另一个物体很有用。 假设你有两个对象,其中一个紧跟着另一个。 我们希望跟随者的旋转始终面对它所跟随的东西。 FRotationMatrix 的构造方法使这一过程变得容易。
首先创建新的类:

添加代码:
FollowActorComponent.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "GameFramework/Actor.h"
#include "FollowActorComponent.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class NEWTUTORIALPROJECT_API UFollowActorComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UFollowActorComponent();
UPROPERTY(EditAnywhere)
AActor * target;
protected:
// Called when the game starts
virtual void BeginPlay() override;
public:
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};
FollowActorComponent.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "FollowActorComponent.h"
// Sets default values for this component's properties
UFollowActorComponent::UFollowActorComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UFollowActorComponent::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UFollowActorComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
FVector toFollow = target->GetActorLocation() - GetOwner()->GetActorLocation();
FMatrix rotationMatrix = FRotationMatrix::MakeFromXZ(toFollow, GetOwner()->GetActorUpVector());
GetOwner()->SetActorRotation(rotationMatrix.Rotator());
}
编译完成后,布局场景:

添加组件:

选择目标为球:

属性设置为可移动:

运行后我们可以看到方块转为面向这个球:

总结:
通过调用正确的函数可以让一个对象看到另一个对象,这取决于对象的计算方向。 通常,我们需要重新定位 x 轴(向前) ,同时指定 y 轴(右)或 z 轴(向上)向量(FRotationMatrix: : MakeFromXY ())。 例如,为了让一个参与者沿着一个 lookAlong 向量的方向看,让它的右边朝右,我们为它构造并设置 FRotationMatrix,如下所示:
FRotationMatrix rotationMatrix = FRotationMatrix::MakeFromXY(lookAlong, right );
actor->SetActorRotation( rotationMatrix.Rotator() );