<style>.lazy{display:none}</style> Skip to main content
Tag

interface

Unreal C++ – Puzzle Mechanics – Pressure Plates and Doors by moving Static Meshes & using Interfaces

By Props, Puzzle, Tutorial, Unreal No Comments

Hey guys,

This new set of tutorials is meant to tackle re-creating puzzle mechanics from our favorite games, starting with pressure plates and doors.

The project files for this video & article can be found on our GitHub page.

To get started we need to create four elements that will comprise our puzzle scene:

  • First we need to extend a Static Mesh Component so we can make it move around.
  • We need a pressure plate object that will handle the triggering of other elements in the level.
  • We need elements in the level that will be affected by the trigger ie) doors / windows
  • And lastly we need an interface that will allow for ease of communication between the last two elements.

So let’s start by creating a custom Static Mesh Component. Below is the header definition.

UENUM(BlueprintType)
enum class ERotationAxis : uint8
{
  Yaw, Pitch, Roll
};

UENUM(BlueprintType)
enum class ELocationAxis : uint8
{
  X, Y, Z
};

UENUM(BlueprintType)
enum class EMovementType : uint8
{
  Location, Rotation
};

/**
 * 
 */
UCLASS()
class PUZZLE1_API UMovableStaticMeshComponent : public UStaticMeshComponent
{
  GENERATED_BODY()

public:

  UMovableStaticMeshComponent();

  virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
  virtual void BeginPlay() override;

  UFUNCTION(BlueprintCallable)
  void Move(bool bTriggered);

  UFUNCTION()
  void OnMove();

  UFUNCTION()
  void OnMoveFinished();

  bool IsMoving() const { return bIsMoving; }
  bool IsTriggered() const { return bIsTriggered; }

public:
  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Movement")
  UCurveFloat* MoveCurve;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Movement")
  EMovementType MovementType;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Movement", meta=(EditCondition="MovementType == EMovementType::Rotation"))
  ERotationAxis RotateAxis;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Movement", meta=(EditCondition="MovementType == EMovementType::Location"))
  ELocationAxis LocationAxis;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Movement")
  bool bIsReversed;

private:
  void UpdateRotation(float CurveValue);
  void UpdateLocation(float CurveValue);

private:
  bool bIsMoving;
  FTimeline MoveTimeline;

  bool bIsTriggered;
  float PreviousTimelineValue;
};

Then we can define the inner workings of our component

UMovableStaticMeshComponent::UMovableStaticMeshComponent()
{
  PrimaryComponentTick.bCanEverTick = true;
}

void UMovableStaticMeshComponent::BeginPlay()
{
  Super::BeginPlay();

  if(MoveCurve)
  {
    FOnTimelineFloat TimelineCallback;
    FOnTimelineEventStatic TimelineFinishCallback;

    TimelineCallback.BindUFunction(this, FName("OnMove"));
    TimelineFinishCallback.BindUFunction(this, FName("OnMoveFinished"));

    MoveTimeline.AddInterpFloat(MoveCurve, TimelineCallback);
    MoveTimeline.SetTimelineFinishedFunc(TimelineFinishCallback);
  }
}

void UMovableStaticMeshComponent::TickComponent(float DeltaTime, ELevelTick Tick, FActorComponentTickFunction* ThisTickFunction)
{
  Super::TickComponent(DeltaTime, Tick, ThisTickFunction);

  if(bIsMoving)
  {
    MoveTimeline.TickTimeline(DeltaTime);
  }
}

void UMovableStaticMeshComponent::Move(bool bTriggered)
{
  bIsTriggered = bTriggered;

  if(bTriggered)
  {
    if(MoveTimeline.IsReversing())
    {
      MoveTimeline.Play();
    }
    else
    {
      MoveTimeline.PlayFromStart();	
    }
  }
  else
  {
    MoveTimeline.Reverse();
  }

  bIsMoving = true;
}

void UMovableStaticMeshComponent::OnMove()
{
  const float PlaybackPosition = MoveTimeline.GetPlaybackPosition();
  float CurveValue = MoveCurve->GetFloatValue(PlaybackPosition);

  if(bIsReversed)
  {
    CurveValue = -CurveValue;
  }

  const float AdjustedValue = CurveValue - PreviousTimelineValue;

  if(MovementType == EMovementType::Location)
  {
    UpdateLocation(AdjustedValue);
  }
  else if(MovementType == EMovementType::Rotation)
  {
    UpdateRotation(AdjustedValue);
  }

  PreviousTimelineValue = CurveValue;
}

void UMovableStaticMeshComponent::OnMoveFinished()
{
  bIsMoving = false;
}

void UMovableStaticMeshComponent::UpdateRotation(float CurveValue)
{
  FRotator NewRotation = GetRelativeRotation();

  switch(RotateAxis)
  {
    case ERotationAxis::Pitch:
      NewRotation.Pitch += CurveValue;
      break;
    case ERotationAxis::Roll:
      NewRotation.Roll += CurveValue;
      break;
    case ERotationAxis::Yaw:
      NewRotation.Yaw += CurveValue;
      break;
    default:
      break;
  }

  SetRelativeRotation(NewRotation);
}


void UMovableStaticMeshComponent::UpdateLocation(float CurveValue)
{
  FVector NewLocation = GetRelativeLocation();

  switch(LocationAxis)
  {
    case ELocationAxis::X:
      NewLocation.X += CurveValue;
      break;
    case ELocationAxis::Y:
      NewLocation.Y += CurveValue;
      break;
    case ELocationAxis::Z:
      NewLocation.Z += CurveValue;
      break;
    default:
      break;
  }

  SetRelativeLocation(NewLocation);
}

As you can see we pass the majority of the work two the two callback functions our timeline is interfacing with: OnMove and OnMoveFinished.

TimelineCallback.BindUFunction(this, FName("OnMove")); 
TimelineFinishCallback.BindUFunction(this, FName("OnMoveFinished"));

OnMove handles the actual position / rotation of the static mesh relative to it’s parent base mesh object.

By overwriting the components Tick Component function we can start / stop the timeline which in turn affects the behavior of our static mesh.

So let’s see how this component can now be used to create a pressure plate.

Let’s define the header first.

UCLASS()
class PUZZLE1_API APressurePlateTrigger : public AActor
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  APressurePlateTrigger();

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

public:	
  // Called every frame
  virtual void Tick(float DeltaTime) override;
  UFUNCTION()
  void OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
  UFUNCTION()
  void OnEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);

private:
  void Interact(bool bIsInteracting);

public:
  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(AllowPrivateAcess = "true"), Category = "Trigger")
  UStaticMeshComponent* BaseMesh;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(AllowPrivateAcess = "true"), Category = "Trigger")
  UMovableStaticMeshComponent* MoveableMesh;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta=(AllowPrivateAcess = "true"), Category = "Trigger")
  USphereComponent* OverlapComponent;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Trigger")
  bool bIsDisabled;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Trigger")
  bool bResetTrigger;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Trigger")
  TArray<FName> TargetTags;

private:
  bool bIsTriggered;
};

Based on this definition we can see there are a couple of parts that go into our pressureplate.

We have a Static Mesh that acts as our base and a Movable Static Mesh Component as the piece that will go down as our character steps on it.

Lastly we use the overlap of our Sphere Component to trigger the behavior.

// Sets default values
APressurePlateTrigger::APressurePlateTrigger()
{
 	// 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;

  BaseMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Base Mesh"));
  SetRootComponent(BaseMesh);

  MoveableMesh = CreateDefaultSubobject<UMovableStaticMeshComponent>(TEXT("Movable Mesh"));
  MoveableMesh->SetupAttachment(BaseMesh);

  OverlapComponent = CreateDefaultSubobject<USphereComponent>(TEXT("Overlap Area"));
  OverlapComponent->SetupAttachment(MoveableMesh);
}

// Called when the game starts or when spawned
void APressurePlateTrigger::BeginPlay()
{
  Super::BeginPlay();

  OverlapComponent->OnComponentBeginOverlap.AddDynamic(this, &ThisClass::OnBeginOverlap);
  OverlapComponent->OnComponentEndOverlap.AddDynamic(this, &ThisClass::OnEndOverlap);
}

// Called every frame
void APressurePlateTrigger::Tick(float DeltaTime)
{
  Super::Tick(DeltaTime);

}

void APressurePlateTrigger::Interact(bool bIsInteracting)
{
  TArray<AActor*> InteractableActors;
  UGameplayStatics::GetAllActorsWithInterface(GetWorld(), UInteractableInterface::StaticClass(), InteractableActors);

  for(AActor* Actor : InteractableActors)
  {
    FName InteractTag = IInteractableInterface::Execute_GetInteractTag(Actor);
    for(FName Tag : TargetTags)
    {
      if(InteractTag.IsEqual(Tag, ENameCase::IgnoreCase))
      {
        IInteractableInterface::Execute_Interact(Actor, bIsInteracting);
      }
    }
  }
}

void APressurePlateTrigger::OnBeginOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
  if(!bIsDisabled && !bIsTriggered)
  {
    MoveableMesh->Move(true);
    Interact(true);

    bIsTriggered = true;
  }
}

void APressurePlateTrigger::OnEndOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
  if(!bIsDisabled && bResetTrigger)
  {
    MoveableMesh->Move(false);
    Interact(false);

    bIsTriggered = false;
  }
}

Since we offloaded the majority of the work to our Movable Static Mesh Component you will notice that this actor is really not doing much of anything.

It handles the Begin and End overlap states to simply notify the movable component that it needs to perform some work.

The only tricky bit is examining the world for our affected components. This is done by using the TargetTags against any actor that implements a specific interface.

TArray<AActor*> InteractableActors;
UGameplayStatics::GetAllActorsWithInterface(GetWorld(), UInteractableInterface::StaticClass(), InteractableActors);

for(AActor* Actor : InteractableActors)
{
  FName InteractTag = IInteractableInterface::Execute_GetInteractTag(Actor);
  for(FName Tag : TargetTags)
  {
    if(InteractTag.IsEqual(Tag, ENameCase::IgnoreCase))
    {
      IInteractableInterface::Execute_Interact(Actor, bIsInteracting);
    }
  }
}

Using UGameplayStatics::GetAllActorsWithInterface we can find all the appropriate actors and then use the interface calls directly to call the specific methods on t hose actors.

Let’s go ahead and define our interface as we haven’t done that yet.

// This class does not need to be modified.
UINTERFACE(MinimalAPI)
class UInteractableInterface : public UInterface
{
  GENERATED_BODY()
};

/**
 * 
 */
class PUZZLE1_API IInteractableInterface
{
  GENERATED_BODY()

  // Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
  UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Interact")
  FName GetInteractTag();

  UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Interact")
  void Interact(bool bInteracting);
};

The two methods of GetInteractTag and Interact is what our doors / windows / chests etc will have to implement in order for our pressure plate to work.

We are going to create a basic actor that similar to our pressure plate actor only contains a few meshes but inherits our new interface.

UCLASS()
class PUZZLE1_API AMovingStaticMeshActor : public AActor, public IInteractableInterface
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  AMovingStaticMeshActor();

  virtual FName GetInteractTag_Implementation() override;
  virtual void Interact_Implementation(bool bInteracting) override;

  bool IsDisabled() const { return bIsDisabled; }

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

public:	
  // Called every frame
  virtual void Tick(float DeltaTime) override;


public:
  UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "Moving")
  UStaticMeshComponent* BaseMesh;

  UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"), Category = "Moving")
  UMovableStaticMeshComponent* MovableMesh;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Moving")
  FName InteractTag;

  UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Moving")
  bool bIsDisabled;
};

The other property we need to ensure is available to our new actor is the InteractTag which our GetInteractTag method returns. This is important as we use those values do to a string match.

Now let’s define the body of our new actor.

// Sets default values
AMovingStaticMeshActor::AMovingStaticMeshActor()
{
 	// 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;

  BaseMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Base Mesh"));
  SetRootComponent(BaseMesh);

  MovableMesh = CreateDefaultSubobject<UMovableStaticMeshComponent>(TEXT("Movable Mesh"));
  MovableMesh->SetupAttachment(GetRootComponent());
}

// Called when the game starts or when spawned
void AMovingStaticMeshActor::BeginPlay()
{
  Super::BeginPlay();
}

// Called every frame
void AMovingStaticMeshActor::Tick(float DeltaTime)
{
  Super::Tick(DeltaTime);
}

FName AMovingStaticMeshActor::GetInteractTag_Implementation()
{
  return InteractTag;
}

void AMovingStaticMeshActor::Interact_Implementation(bool bInteracting)
{
  if(!bIsDisabled)
  {
    MovableMesh->Move(bInteracting);
  }
}

Again very simple logic as all we are doing is triggering the Movable Static Mesh Component when someone interacts with this actor.

This actor can now be used to represent a door, window, trunk of a car, or even an elevator. Basically anything that has a single component that you need to move or rotate this will give you that flexbility.

Please check out the video and the GitHub page for more details.

Additionally find the Blueprint version of this tutorial on our Patreon.

Unreal Engine C++ Fundamentals – Interfaces!

By Development, Tutorial, Unreal 3 Comments

Hey guys,

Today we resume our C++ Fundamentals lessons by looking at interfaces and how they can help simply our life by allowing for common contracts to be shared by different game actors.

As usual you can find the start project on our GitHub page.

What is an interface ? Tell me !

An interface is an abstract definition of a contract. What this means is an interface defines how our class can be interfaced ( hah ! ) with while keeping the implementation details away.

More than that it allows us to create a common method signature between various disparate objects.

Consider I have an interface that has a method on it called “DoStuff” and I have two objects, Dog and Person, that inherit this interface. When I call Dog->DoStuff he may perform a trick while if I call the same method of Person->DoStuff he may tell me to fuck off and to stop bothering them. But from the point of view of the code interacting with those actors it’s the same behavior.

This allows for a lot of re-use and generic implementations while keeping the details of those implementations specific.

This all seems very abstract, show me code !

So let’s take a look at how an interface class is structured

UINTERFACE(MinimalAPI)
class UInteractiveActor : public UInterface
{
  GENERATED_BODY()
};

/**
 * 
 */
class UE4FUNDAMENTALS09_API IInteractiveActor
{
  GENERATED_BODY()

  // Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:

  UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
  void Interact();
};

As you can see it’s pretty thin in definition, we simply have a class that inherits from UInterface and then defines the method signature of “Interact”.

Excellent now we are cooking with fire, now what ?

Once we have the interface in place we now start including it on our objects. Let’s take a look at our InteractiveProp.

UCLASS()
class UE4FUNDAMENTALS09_API AInteractiveProp : public AActor, public IInteractiveActor
{
  GENERATED_BODY()
  
public:	
  // Sets default values for this actor's properties
  AInteractiveProp();

  UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Interact")
  class UStaticMeshComponent* BaseMesh;

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, BlueprintNativeEvent, Category = "Interact")
  void Interact();	// prototype declaration
  virtual void Interact_Implementation() override;	// actual implementation of our interact method

private:
  bool bIsBig;
};

The major thing to note is that in order to leverage the interface, we modify our class signature to bring in “IInteractiveActor”

class UE4FUNDAMENTALS09_API AInteractiveProp : public AActor, public IInteractiveActor

Then we overwrite the Interact method by first declaring the prototype method signature and then the implementation one. Please note that the “_Implementation” is important and has to be exact for the reflection mechanic in Unreal to process your interface + implementation.

UFUNCTION(BlueprintCallable, BlueprintNativeEvent, Category = "Interact")
void Interact();	// prototype declaration
virtual void Interact_Implementation() override;	// actual implementation of our interact method

So that was pretty straight forward, now how do I use these guys ?

To execute interface definitions we have a few ways of going about.

First we need to determine if an object uses an interface and we have two ways of checking that.

  1. Based on the ImplementsInterface check
  2. Using a cast to an interface object

Here is the first example

InteractHit.GetActor()->GetClass()->ImplementsInterface(UInteractiveActor::StaticClass())

And the second one

IInteractiveActor* InteractiveActor = Cast<IInteractiveActor>(InteractHit.GetActor());
if(InteractiveActor)
{
  // do stuff
}

Once you determine if an object has an interface the way you execute a call on that object is by passing it into the interface “Execute_” call.

IInteractiveActor::Execute_Interact(InteractHit.GetActor());

This basically says, for interface InteractiveActor Execute the method Interact and pass in our Actor on which that method will be triggered.

Here is a full code block that does this logic using a line trace fired from the player against an object.

void AUE4Fundamentals09Character::Interact()
{
  FVector Start;
  FVector End;

  FVector PlayerEyesLoc;
  FRotator PlayerEyesRot;

  GetActorEyesViewPoint(PlayerEyesLoc, PlayerEyesRot);

  Start = PlayerEyesLoc;
  End = PlayerEyesLoc + (PlayerEyesRot.Vector() * LineTraceDistance);

  FCollisionQueryParams TraceParams(FName(TEXT("InteractTrace")), true, this);

  FHitResult InteractHit = FHitResult(ForceInit);

  bool bIsHit = GetWorld()->LineTraceSingleByChannel(InteractHit, Start, End, ECC_GameTraceChannel3, TraceParams);

  if(bIsHit)
  {
    Log(ELogLevel::WARNING, InteractHit.Actor->GetName());
    // start to end, green, will lines always stay on, depth priority, thickness of line
    DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 5.f, ECC_WorldStatic, 1.f);

    // implements interface
    if(InteractHit.GetActor()->GetClass()->ImplementsInterface(UInteractiveActor::StaticClass()))
    {
      IInteractiveActor::Execute_Interact(InteractHit.GetActor());
    }
  }
}

That’s it folks !

In addition to the video here are a few resources for further reading: