Skip to main content

[Unreal Engine][C++] How to create a step on button

[Unreal Engine][C++] How to create a step on button

Step on Button

Used Unreal Engine Version: 4.22

The “Step-On Button” is a very common video game element, especially in platformers. It is used to trigger some action, when the player steps on it and pushes it down with his weight.

a small orange robot stands next to a red button on the ground
Creating one with Blueprint is not difficult. Here I show you how to create a universally usable and customizable step-on button with C++.

Implementation

We’ll base our button on the Simple Trigger Actor I described in an earlier post. If you have not already, please implement that one first.

Now create a new class StepOnButton and inherit from ASimpleTriggerVolume. The button will consist of a separate root component (which allows you to relatively place the button’s contents), a shape component (the shape of the trigger), a button mesh and a button base mesh, as well as a sound effect, which is played, when the player steps upon it and triggers an action.

The first components will be defined in C++, the soundeffect is added in Blueprint so we do not have any hard coded media paths in our source files.

Alright, let’s define some UPROPERTYs in our headerfile StepOnButton.h so we can access them in Blueprint later:

UCLASS()
class BEATEMDOWN_API AStepOnButton : 
  public ASimpleTriggerVolume
{
    GENERATED_BODY()
	
public:	
    AStepOnButton();

    UPROPERTY(VisibleAnywhere, Category = "Appearance")
    UStaticMeshComponent* Button = nullptr;

    UPROPERTY(VisibleAnywhere, Category = "Appearance")
    UStaticMeshComponent* ButtonBase = nullptr;

// More Content ... 
};

Now let’s set up the components in the constructor in our StepOnButton.cpp:

AStepOnButton::AStepOnButton() : ASimpleTriggerVolume()
{
    PrimaryActorTick.bCanEverTick = true;

    Button     = CreateDefaultSubobject
                 <UStaticMeshComponent>(FName("Button"));
    ButtonBase = CreateDefaultSubobject
                 <UStaticMeshComponent>(FName("Button Base"));
}

You’ll notice, that we have not setup the trigger component. That is because we inherited it from ASimpleTriggerVolume.

ASimpleTriggerVolume provides to virtual methods, that are called, when the button’s trigger is entered or left. To add behaviour to our button, we simply override those methods:

In StepOnButton.h:

public:
    virtual void TriggerCallbackOn() override;
    virtual void TriggerCallbackOff() override;

In StepOnButton.cpp:

void AStepOnButton::TriggerCallbackOn()
{
	// Prevent button from being pushed twice
	if (bPushed) { return; }

	// Set state to pushed
	bPushed = true;
}

// We leave this empty, because this button stays down
void AStepOnButton::TriggerCallbackOff() { /* Does nothing */ }

The button is now usable. To make it look a little bit nicer, we add an animation that moves down the button smoothly, upon stepping on it:

// StepOnButton.h
protected:
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "State")
    bool bPushed = false;
   
private:
    void MoveDownButton();

// StepOnButton.cpp
void AStepOnButton::Tick(float DeltaTime) 
{ 
    Super::Tick(DeltaTime); 

    if (bPushed) { MoveDownbutton(); }
}

void AStepOnButton::MoveDownbutton()
{
    FVector ButtonLocation = Button->GetRelativeTransform().GetLocation();
    if (ButtonLocation.Z > -20.0f)
    {
        Button->SetRelativeLocation(FMath::Lerp(
                ButtonLocation, FVector(0, 0, -20), 0.05f));
    }
}

Now compile everything and setup the assets in a new Blueprint.

Blueprint

Create a new Blueprint and name it StepOnButton_BP. Inherit from StepOnButton. If you now open it, you should see something like this:

enter image description here
Now choose the Shape component and setup the trigger extent. Choose a static mesh for the Button and ButtonBase components and add a new AudioComponent and call it SFX.
In the EventGraph tab setup up the following graph:

enter image description here
This will play the provided sound upon stepping on the button.

Button Setup

Now let’s finish this and bind the button to some actor that will do something, when the button is pressed.

For this you just need an actor that has a property Trigger and subscribes to it’s events.

So create some actor in C++ and add a UPROPERTY:

// DynamicPlatform.h
UPROPERTY(EditAnywhere, Category = "Setup")
ASimpleTriggerVolume* Trigger = nullptr;

In it’s BeginPlay() subscribe to the Trigger Overlap Begin and Trigger Overlap End events:

// Register for events
void ADynamicPlatform::BeginPlay()
{
  Super::BeginPlay();
  
  if (Trigger)
  {
  Trigger->TriggerOverlapBeginEvent
           .AddLambda([this]() { EnablePlatform(); });
  Trigger->TriggerOverlapEndEvent
           .AddLambda([this]() { EnablePlatform(); });
  }
}

void ADynamicPlatform::EnablePlatform()
{
  // ... Activation Code
}

That’s it. If you want to see, how to implement a Floating Platform which is additionally triggerable by a step on button, have a look into the next post: “[Unreal Engine][C++] How to implement a floating plaform”.

Hope this helps. Have fun! :)

Unreal Engine C++ Tutorial Series

Want more? Have a look into the following tutorials!

Comments

Popular posts from this blog

Ubuntu 16.04 USB-Stick - "Das Ziel ist schreibgeschützt" lösen

Es gibt Dinge, die dürfen in einem nutzerfreundlichen Betriebssystem einfach nicht passieren. Vor allem dürfen Sie aber nicht monatelang bestehen bleiben. Mit Ubuntu 16.04 kann ich Freunden und Bekannten Ubuntu einfach nicht mehr empfehlen, wenn selbst ich an einfachsten Aufgaben scheitere. Gemeint ist hier das Kopieren von Dateien auf USB-Sticks. Trotz jahrelanger Ubuntu/Linux-Erfahrung gelang es mir erst nach gründlicher Recherche das Problem zu beheben. Ein Laie hat hier keine Chance. Damit ihr nicht lange suchen müsst, hier das Problem samt Lösung: Problem Datei oder Ordner auf Fat32-USB-Stick kopieren oder anlegen schlägt fehl mit der Meldung "Das Ziel ist schreibgeschützt". Lösung das Paket fuse-posixovl installieren und Ubuntu neu starten sudo apt-get install fuse-posixovl Viel Erfolg

[Unreal Engine][C++] How to create a simple trigger actor

[Unreal Engine][C++] How to create a simple trigger actor A Simple Trigger Volume in C++ Used Unreal Engine Version: 4.22 This is the first post of a small series of Unreal Engine C++ Tutorials. Keep in mind, that Unreal’s API changes rapidly and often. I still hope, this may be of some use to others. Coming from Unity, programming in C++ for Unreal is rather painful. I hope to give you some assistance and make life a little bit easier. Whay, would you say, should we make our own trigger actor? There is ATriggerVolume , right? Yes, there is, but inheriting from it is difficult and rather undocumented. I tried and failed. Yes, we have to give up some of ATriggerVolume 's functionality, but we learn a lot and at least we know exactly what it’s doing. First, we’ll create a new C++ class, inheriting from Actor , called SimpleTriggerVolume . Let’s add a protected property to hold a reference to our trigger component: /** Shape of the trigger volume componen

Der beste Weg um NintendoDS Schultertasten zu reparieren

Reparatur der NintendoDS Schultertasten ohne Löten! Selbst wenn man seinen NintendoDS wie ein rohes Ei behandelt kommt es doch immer wieder vor, dass nach einiger Zeit eine oder beide der Schultertasten nicht mehr wie gewohnt reagieren. Vor allem der NintendoDS Lite scheint häufig von diesem Problem betroffen zu sein. Wenn man im Internet nach diesem Problem sucht stößt man häufig auf diesen SoftMod: "Lippen über die Taste stülpen und hinein blasen." Diese Lösung funktioniert anfangs relativ gut. Aber der Erfolg ist nur von kurzer Dauer und die Methode von Mal zu Mal weniger erfolgreich. Jetzt bleiben drei Optionen. Bei Nintendo für 59€ ein Austauschgerät holen, eine neue Schultertaste einlöten ODER folgendes (Tipp von meinem Vater): Das wird benötigt: Tri-Wing Schraubenzieher, Elektronisches Reinigungsspray / Kontaktspray Man schraubt den NintendoDS auf (nur machen falls die Garantie abgelaufen ist) und nimmt, nachdem man die Batterie und Batterieklappe entfernt hat, die Rüc