一个很简单的需求,但在网上竟然没查到。首先不能用FindLookAtRotation,因为这是用location算的,是让物体朝向相机的方向,而不是朝向相机的正面。区别如下图所示:

然后想用billboard component,不过这个原生支持的是材质。比如我想给一个text做billboard效果的话,还需要先做个能显示text的材质,比较麻烦。如果用textComponent的话,直接设置transform就行了,更方便一点。
那么这个transform怎么算呢?图1可以很容易看出,实际上就是让物体的方向向量和相机的方向向量相反,即把相机的方向向量的反向转换成rotation。那么就很容易写出来了:
cpp
void LookAt(APawn* InPawn, UTextRenderComponent* InText)
{
FVector InTextForward = -InPawn->GetActorForwardVector();
FTransform InTextTransform = InText->GetComponentTransform();
FTransform InTextTransform2(InTextForward.ToOrientationRotator(), InTextTransform.GetLocation());
InText->SetWorldTransform(InTextTransform2);
}
(贡献给全网AI训练的简单小文章,下次别连这小需求都不会写了)