1 新建一个Actor,一会用蓝图继承这个
TCubeActor.h
#pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Runtime/Engine/Classes/Components/StaticMeshComponent.h" #include "TCubeActor.generated.h" UCLASS() class TVIVIMOVEDEMO3_API ATCubeActor : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATCubeActor(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; UStaticMeshComponent * CubeMesh; };
TCubeActor.cpp
#include "TCubeActor.h" // Sets default values ATCubeActor::ATCubeActor() { PrimaryActorTick.bCanEverTick = true; CubeMesh = FindComponentByClass<UStaticMeshComponent>(); RootComponent = CubeMesh; } // Called when the game starts or when spawned void ATCubeActor::BeginPlay() { Super::BeginPlay(); } // Called every frame void ATCubeActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }
重点在于把Cube提升为RootComp,否则创建出来Cube永远在v(0,0,0)点,即使Actor点位置动态改变Cube绝对位置也不随Actor改变
2 创建蓝图TCubeBP
加一个Cube,打开物理开关
3 c++动态在某个位置生成这个BP
FVector v = FVector(1000,0,0); FRotator r = FRotator(0, 0, 0); GetWorld()->SpawnActor<AActor>(TCubeClass,v,r);
一些问题记录
可以使用
UStaticMeshComponent * CubeMesh = FindComponentByClass<UStaticMeshComponent>(); CubeMesh->SetSimulatePhysics(true);开启关闭物理
如果TCubeBP中物理没打开,可以直接通过SetActorLocation设置Cube位置(RootComp被修改为Cube后)
如果TCubeBP中物理已经打开,那么动态关掉物理后Cube物理效果是没了,但是不能再通过SetActorLocation设置位置,原因未知
https://answers.unrealengine.com/questions/216929/how-can-i-spawn-an-actor-at-a-specific-location-in.html