- Create a new C++ class derived from the StaticMeshActor class using the editor wizard; call it SlidingDoor.
- Add the following text that's in bold to the new class:
class CHAPTER_09_API ASlidingDoor : public AStaticMeshActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASlidingDoor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintCallable, Category = Door)
void Open();
UPROPERTY()
bool IsOpen;
UPROPERTY()
FVector TargetLocation;
};
- Create the class implementation by adding the following text in bold to the .cpp file:
#include "SlidingDoor.h"
#include "ConstructorHelpers.h"
// Sets default values
ASlidingDoor::ASlidingDoor()
{
// Set this actor to call Tick() every frame. You can turn
// this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
auto MeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>
(TEXT("StaticMesh'/Engine/BasicShapes/Cube.Cube'"));
UStaticMeshComponent * SM = GetStaticMeshComponent();
if (SM != nullptr)
{
if (MeshAsset.Object != nullptr)
{
SM->SetStaticMesh(MeshAsset.Object);
SM->SetGenerateOverlapEvents(true);
}
SM->SetMobility(EComponentMobility::Movable);
SM->SetWorldScale3D(FVector(0.3, 2, 3));
}
SetActorEnableCollision(true);
IsOpen = false;
PrimaryActorTick.bStartWithTickEnabled = true;
}
// Called when the game starts or when spawned
void ASlidingDoor::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ASlidingDoor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
if (IsOpen)
{
SetActorLocation(FMath::Lerp(GetActorLocation(),
TargetLocation, 0.05));
}
}
void ASlidingDoor::Open()
{
TargetLocation = ActorToWorld().TransformPositionNoScale(
FVector(0, 0, 200));
IsOpen = true;
}
- Compile your code and launch the editor.
- Drag a copy of your door out into the level:
An easy way to have objects fall to the ground is by using the End key with the object you want to drop selected.
- Make sure you have your SlidingDoor instance selected, then open the Level blueprint by going to Blueprints | Open Level Blueprint. Right-click on the empty canvas and expand Call function on Sliding Door 1:
- Expand the Door section and then select the Open function:
- Link the execution pin (white arrow) from Event BeginPlay to the white arrow on the Open node, as shown in the following screenshot:
- Play your level and verify that the door moves up as expected when Open is invoked on your door instance: