1.销毁Actor
1.Actor中存在Destory()函数和Destoryed()函数
Destory()函数是成员函数,它会立即标记 Actor
为销毁状态,并且会从场景中移除该 Actor
。它会触发生命周期中的销毁过程,调用 Destroy()
后,Actor
立即进入销毁过程。具体来说,它会开始执行 BeginDestroy()
和 EndDestroy()
,并且会销毁 Actor
本身及其所有组件
Destroyed()函数是虚函数(或者是事件函数),它在 Actor
被销毁后被自动调用。你可以在 Destroyed()
中执行一些销毁后的清理工作,Destroyed()
是一个回调函数,当 Actor
销毁过程完成时(通常是调用 Destroy()
后)会被自动调用。可以重写Destoryed()函数完成Actor销毁后的一些操作
2.Actor在什么时候会被完全销毁
1.调用 Destroy()
时,Unreal Engine 不会立即释放 Actor
的内存,而是:
- 标记
Actor
为待销毁状态 (bPendingKill = true
)。 - 移除
Actor
及其组件,停止它的 Tick 和物理模拟。 - 触发
EndPlay()
事件(如果Actor
还在BeginPlay()
之后)。 - 触发
Destroyed()
事件,让子类可以在销毁前执行额外逻辑。 Actor
从世界中移除,停止 Tick 和物理模拟
2.调用Destroyed()
- 允许
Actor
在销毁前执行自定义逻辑
3.UE中的GC机制
当前阶段会释放掉Actor的内存。
2.移动Actor
1.使用MoveComponent()函数,
void ASpawnActor::SetActorLocation()
{
UStaticMeshComponent* RootComp = Cast<UStaticMeshComponent>(GetRootComponent());
if (RootComp)
{
// 定义你想要移动的偏移量
FVector Offset(0.f, 0.f, -10.f); // 向Z轴移动10单位
// 使用MoveComponent来平滑移动组件
RootComp->MoveComponent(Offset, FRotator::ZeroRotator, true);
//UE_LOG(LogTemp, Warning, TEXT("move ment component"));
}
}
我当前的RootComponent是UStaticMeshComponent类型的,如果使用SetupAttachment附加到原本的RootComponent也可以实现,MoveCompoennt是USceneComponent类中的成员函数,只要继承自这个类都可以调用MoveCompoennt函数
2.创建一个UMoveMentComponent的组件
创建C++类ActorMovementComponent继承自MoveMentComponent,在,Actor中定义指针,在Actor的构造中初始化这个指针
UPROPERTY(VisibleAnywhere, Category = "Move");
UActorMovementComponent* ActorMovementComponent;
ActorMovementComponent = CreateDefaultSubobject<UActorMovementComponent>(TEXT("Move"));
ActorMovementComponent类中实现(TickComponent是虚函数,重写一份,记得)
void UActorMovementComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
//一定记得要写这行
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// 速度和加速度可以从Actor 中设置,也可以默认
// 更新速度,应用加速度
FVelocity += Acceleration * DeltaTime;
// 限制最大速度
if (FVelocity.Size() > MaxSpeed)
{
FVelocity = FVelocity.GetSafeNormal() * MaxSpeed;
}
// 更新 Actor 位置
FVector NewLocation = GetOwner()->GetActorLocation() + (FVelocity * DeltaTime);
GetOwner()->SetActorLocation(NewLocation);
// 重置加速度(如果希望每帧都控制加速度,可以在外部控制)
Acceleration = FVector::ZeroVector;
}
3.制作一个简单的空气墙
1.创建一个UBoxComponent设置SetVisibility(false)将可视性为变成false,设置碰撞类型
SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics);
SetCollisionResponseToAllChannels(ECR_Block); // 使得所有物体都会被阻挡
SetCollisionResponseToChannel(ECollisionChannel::ECC_Camera,ECollisionResponse::ECR_Ignore);
2.创建对应蓝图,拖拽到场景中,调整大小。