UE4C++写一个开门事件
时间: 2023-07-13 18:18:29 浏览: 138
好的,以下是一个简单的UE4 C++代码示例,用于触发门的开启事件:
首先,创建一个继承自Actor的蓝图类,将门模型拖放到该类中,并为门添加一个Box组件作为门的触发器。
在.h文件中添加以下代码:
```c++
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyDoor.generated.h"
UCLASS()
class MYPROJECT_API AMyDoor : public AActor
{
GENERATED_BODY()
public:
AMyDoor();
protected:
UPROPERTY(VisibleAnywhere, Category = "Components")
class UStaticMeshComponent* DoorMesh;
UPROPERTY(VisibleAnywhere, Category = "Components")
class UBoxComponent* TriggerBox;
UPROPERTY(EditAnywhere, Category = "Properties")
float OpenAngle = 90.0f;
UPROPERTY(EditAnywhere, Category = "Properties")
float DoorCloseDelay = 2.0f;
float LastDoorOpenTime;
UPROPERTY(EditAnywhere, Category = "Properties")
float DoorOpenSpeed = 0.8f;
UPROPERTY(EditAnywhere, Category = "Properties")
float DoorCloseSpeed = 2.0f;
UFUNCTION()
void OnDoorOverlapBegin(class AActor* OverlappedActor, class AActor* OtherActor);
UFUNCTION()
void OnDoorOverlapEnd(class AActor* OverlappedActor, class AActor* OtherActor);
public:
virtual void Tick(float DeltaTime) override;
};
```
在.cpp文件中添加以下代码:
```c++
#include "MyDoor.h"
#include "Components/StaticMeshComponent.h"
#include "Components/BoxComponent.h"
AMyDoor::AMyDoor()
{
PrimaryActorTick.bCanEverTick = true;
DoorMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("DoorMesh"));
RootComponent = DoorMesh;
TriggerBox = CreateDefaultSubobject<UBoxComponent>(TEXT("TriggerBox"));
TriggerBox->SetupAttachment(RootComponent);
TriggerBox->OnComponentBeginOverlap.AddDynamic(this, &AMyDoor::OnDoorOverlapBegin);
TriggerBox->OnComponentEndOverlap.AddDynamic(this, &AMyDoor::OnDoorOverlapEnd);
LastDoorOpenTime = 0.0f;
}
void AMyDoor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (GetWorld()->TimeSeconds - LastDoorOpenTime > DoorCloseDelay)
{
float CurrentYaw = DoorMesh->GetComponentRotation().Yaw;
float TargetYaw;
if (CurrentYaw > 0)
{
TargetYaw = 0.0f;
}
else
{
TargetYaw = OpenAngle;
}
float NewYaw = FMath::FInterpTo(CurrentYaw, TargetYaw, DeltaTime, DoorCloseSpeed);
DoorMesh->SetRelativeRotation(FRotator(0.0f, NewYaw, 0.0f));
}
}
void AMyDoor::OnDoorOverlapBegin(class AActor* OverlappedActor, class AActor* OtherActor)
{
if (OtherActor && OtherActor != this)
{
LastDoorOpenTime = GetWorld()->TimeSeconds;
float CurrentYaw = DoorMesh->GetComponentRotation().Yaw;
float NewYaw = FMath::FInterpTo(CurrentYaw, OpenAngle, GetWorld()->DeltaTimeSeconds, DoorOpenSpeed);
DoorMesh->SetRelativeRotation(FRotator(0.0f, NewYaw, 0.0f));
}
}
void AMyDoor::OnDoorOverlapEnd(class AActor* OverlappedActor, class AActor* OtherActor)
{
if (OtherActor && OtherActor != this)
{
LastDoorOpenTime = GetWorld()->TimeSeconds;
}
}
```
这个代码示例中,我们添加了一个门模型和一个Box组件用作门的触发器。在Box组件上注册了OnComponentBeginOverlap和OnComponentEndOverlap事件,当有物体进入或离开Box时,将触发相应的事件。在OnDoorOverlapBegin事件中,我们通过插值将门旋转到开启的角度,并在LastDoorOpenTime中存储当前时间。在Tick函数中,我们检查LastDoorOpenTime是否超过DoorCloseDelay,如果是,则插值将门旋转回关闭的角度。
最后,将蓝图类添加到场景中,运行游戏并测试门的开启和关闭事件。
阅读全文