Website powered by

How did I deal with… writing an interaction method in C++ for Unreal Engine

This is what the Interact Function declaration, in Player Character / protected section Header looks like:

void Interact(const FInputActionValue& Value);

And this is the implementation in source file:

void ASciFiProjCharacter::Interact(const FInputActionValue& Value)
{
if (OverlappedActor && CanPickup)
{
IInteractInterface* Interface = Cast(OverlappedActor);

if (Interface && (MissionAccomplished == false))
{
Interface->Execute_OnInteract(OverlappedActor, this);
CollectedItems++;
Add_Item.Broadcast();
}
if (CollectedItems == (TotalItems - 1))
{
Interact_OneToGo.Broadcast();
}

if (CollectedItems == TotalItems)
{
CanPickup = false;
MissionAccomplished = true;
Mission_Accomplished.Broadcast();
All_Pickups_Collected.Broadcast();
Interact_Finished.Broadcast();
}
}
else
{
if (OverlappedActor == nullptr && CanPickup == false && MissionAccomplished == false)
{
Interact_Empty.Broadcast();
}
if (OverlappedActor == nullptr && CanPickup == false && MissionAccomplished == true)
{
Interact_Finished.Broadcast();
}
}
}

The advantage of using Interfaces and Delegates is that you are casting only once to the Interface. Because of that, your character's tick, references, and dependencies are clean and you’re executing the interaction only when an Event takes place, rather than on a constant CPU/GPU effort through casting:
1. The player character approaches the pickup, overlaps
2. Pickup changes color and character can pickup
3. UI sends a message
4. You press “E”
5. Counter updates, and
6. UI writes messages/hints.
If you collect enough pickups, the TotalItems number is going to be equal to the number of CollectedItems:
• The event unlocks the exit gates
• UI sends “Mission Accomplished” messages, and
• Game Mode preps end screens.
If you want to see more examples of using programming in real and render time, click on the following case studies links:
Implementing C++ Interface:
https://www.3dartviz.com/skills/skills-tech/implementing-interface-video-game-cpp.html
Delegates for UI and Gameplay:
https://www.3dartviz.com/skills/skills-tech/delegates-communicate-ui-gameplay.html
Adding Input Action in C++
https://www.3dartviz.com/skills/skills-tech/adding-input-action-cpp-ue.html
Programming Gameplay in C++:
https://www.3dartviz.com/skills/skills-tech/programming-gameplay-cpp-ue.html
Programming Python Tool:
https://www.3dartviz.com/skills/skills-tech/programming-automation-tool-python.html

Getting close to pickup and pressing “E”

Getting close to pickup and pressing “E”