天天看點

UE4 移動物體的幾種方法

1,Actor->SetActorLocation

Actor->SetActorLocation()      

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.​

9,UKismetSystemLibrary::MoveComponentTo

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