keywords: UE4, Movement, 移动物体的几种方法

1,Actor->SetActorLocation()

SetActorLocation()不生效,可能原因三两种:

  • RootComponent的Mobility不是Movable
  • 没有RootComponent;如果是纯蓝图actor,拖拽某个component作为root component:
    如果是自定义C++ actor,在构造函数中通过SetRootComponent()设置RootComponent。
  • dedicated server模式下,开启了位移同步,且只在client修改了location,server未修改。

2,AActor::AddActorWorldOffset(), AActor::AddActorLocalOffset()

AddActorWorldOffset与AddActorLocalOffset区别:如果期望Actor沿着某个世界坐标系方向移动,那么使用AddActorWorldOffset并且参数为世界坐标系的DeltaLocation;如果期望Actor沿着当前Actor局部坐标系方向移动,那么使用AddActorLocalOffset并且参数为相对当前Actor的DeltaLocation Offset(比如想做螺旋轨迹但又不想计算其世界空间坐标,那么就用LocalOffset)。

如果使用AddActorWorldOffset或者AddActorLocalOffset移动Character,那么MovementMode必须设置为fly,否则当DeltaLocation较小时,角色会始终往下掉(即使禁用物理模拟),UCharacterMovementComponent::SetMovementMode(EMovementMode::MOVE_Flying);。或者Unpossess Controller。

3,Velocity

ACharacter->GetCharacterMovement()->Velocity += FVector(5.f, 5.f, 0.f);

4,将一个Controller(PlayerController或者AIController)possess到一个Actor上,然后调用:

Controller->MoveTo();

5,将一个Controller(PlayerController或者AIController)possess到一个Actor上,然后调用

GetWorld()->GetNavigationSystem()->SimpleMoveToLocation(Controller, DestLocation);

注意:如果使用Controller->MoveTo或者使用NavigationSystem的Move函数,前提条件是你使用了Navigation组件并build了地形,否则无效。

6,APawn->AddMovementInput

APawn->AddMovementInput(FVector WorldDirection, float ScaleValue = 1.0f, bool bForce = false);

其中WorldDirection是方向,ScaleValue是速率倍速,bForce表示是否忽略Controller中的IgnoreMoveInput属性值,强制移动。

7,UCharacterMovementComponent::AddImpulse

void UCharacterMovementComponent::AddImpulse( FVector Impulse, bool bVelocityChange )

AddImpulse 一般用来做投掷、爆炸、击飞等冲量物理。添加的是一个瞬间的力,之后就不需要每帧做处理了。

注意:AddImpulse 作用对象一般都是 StaticMeshComponent ,而不能是 CollisionComponent,否则无效。且 StaticMeshComponent 要开启物理:SetSimulatePhysics(true) ,否则也无效。

8,UCharacterMovementComponent::AddForce

void UCharacterMovementComponent::AddForce( FVector Force )

如果想让物体保持移动,需要每帧都执行AddForce()函数,也就说如果加速度是实时变化的,那么就可以用AddForce。 两者的区别:
AddForce accounts for delta time and should be used for applying force over more than one frame, AddImpulse does not account for delta time and should be used for single 'pushes', like from an explosion or being thrown by a player. The reason is that if you use AddForce for throwing or an explosion, how far the object moves depends on the framerate at the exact frame the force was applied, rather than being independent of framerate like AddImpulse is.

参考:
https://forums.unrealengine.com/showthread.php?29496-Addforce-and-addimpulse

9,UKismetSystemLibrary::MoveComponentTo

FLatentActionInfo ActionInfo;
ActionInfo.CallbackTarget = this;
UKismetSystemLibrary::MoveComponentTo(TopDownCameraComponent, Location, Rotation, false, false, 1.f, true, EMoveComponentAction::Move, ActionInfo);

一般用来移动Actor身上的Component,例如CameraComponent等。支持平滑移动,可以设置移动到目标Location、Rotation过程的时长。


我所有的自负都来自我的自卑,所有的英雄气概都来自于我内心的软弱,所有的振振有词都因为心中满是怀疑。我假装无情,其实是痛恨自己的深情。我以为人生的意义在于四处游荡流亡,其实只是掩饰至今没有找到愿意驻足的地方。——伊塔洛·卡尔维诺《看不见的城市》