25 UE5 Component 组件系统

2024-05-14  本文已影响0人  游戏开发程序员

组件

组件的分类

组件的更新

image.png

UActorComponent 组件基类

Actor 和 UActorComponent 的关系

继承UActorComponent 的子组件类

USceneComponent

USceneComponent组件类

UPrimitiveComponents组件类(继承USceneComponent)

UInputComponent组件类

UMovementComponent组件类

SensingComponent组件类

PawnNoiseEmitterComponent 组件类

示例代码

UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class UMySceneComponent : public USceneComponent
{
    GENERATED_BODY()

public: 
    UMySceneComponent();

protected:
    // Called when the game starts
    virtual void BeginPlay() override;

public: 
    // Called every frame
    virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;

    // 原始Z点
    UPROPERTY(VisibleAnywhere, Category = "Floating")
    float OriginalZ;

    // 当前方向
    UPROPERTY(VisibleAnywhere, Category = "Floating")
    float CurDirection;
};
// Called when the game starts
void UMySceneComponent::BeginPlay()
{
    Super::BeginPlay();

    // 获取组件所属的Actor
    AActor* OwnerActor = GetOwner();
    if (OwnerActor)
    {
        // 获取当前Actor的位置
        FVector CurrentLocation = OwnerActor->GetActorLocation();

        // 设置递增或递减方向
        OriginalZ = CurrentLocation.Z;
    }
}

// Called every frame
void UMySceneComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
    Super::TickComponent(DeltaTime, TickType, ThisTickFunction);

    // 获取组件所属的Actor
    AActor* OwnerActor = GetOwner();
    if (OwnerActor)
    {
        // 获取当前Actor的位置
        FVector CurrentLocation = OwnerActor->GetActorLocation();

        float NewZ;

        // 设置递增或递减方向
        float MaxFloatingValue = 200.0f;
        if (CurrentLocation.Z > OriginalZ + MaxFloatingValue)
        {
            CurDirection = -1.0f;

            NewZ = OriginalZ + MaxFloatingValue - 1.0f;

            UE_LOG(LogTemp, Warning, TEXT("> CurrentLocation.Z = %f"), CurrentLocation.Z);

        }
        else if (CurrentLocation.Z < OriginalZ)
        {
            CurDirection = 1.0f;

            NewZ = OriginalZ + 1.0f;

            UE_LOG(LogTemp, Warning, TEXT("< CurrentLocation.Z = %f"), CurrentLocation.Z);
        }
        else
        {
            // 计算新的Z轴位置
            NewZ = CurrentLocation.Z + 100.0f * DeltaTime * CurDirection;
        }

        // 设置Actor的新位置
        OwnerActor->SetActorLocation(FVector(CurrentLocation.X, CurrentLocation.Y, NewZ));
    }
}

// 自定义组件
UPROPERTY(VisibleAnywhere, Category = "Switch Components")
class UMySceneComponent* MySceneComponent1;


AMyActor::AMyActor()
{
    // 添加自定义组件
    MySceneComponent1 = CreateDefaultSubobject<UMySceneComponent>(TEXT("MySceneComponent1"));
    MySceneComponent1->SetupAttachment(RootComponent);
}
上一篇下一篇

猜你喜欢

热点阅读