Created
November 15, 2024 17:46
-
-
Save 32teeth/47af46de0ecd9efb01424583e6c75f1c to your computer and use it in GitHub Desktop.
Debounced Input Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "DebouncedInputComponent.h" | |
#include "TimerManager.h" | |
UDebouncedInputComponent::UDebouncedInputComponent() | |
{ | |
PrimaryComponentTick.bCanEverTick = false; | |
DebounceDelay = 0.2f; // Default debounce delay in seconds | |
Threshold = 0.05f; // Default movement threshold | |
LastProcessedValue = 0.0f; // Initial value for comparison | |
} | |
void UDebouncedInputComponent::BeginPlay() | |
{ | |
Super::BeginPlay(); | |
} | |
void UDebouncedInputComponent::UpdateValue(float NewValue) | |
{ | |
// Only process if the change exceeds the threshold | |
if (FMath::Abs(NewValue - LastProcessedValue) >= Threshold) | |
{ | |
// Clear any existing timer to reset debounce delay | |
GetWorld()->GetTimerManager().ClearTimer(DebounceTimerHandle); | |
GetWorld()->GetTimerManager().SetTimer(DebounceTimerHandle, this, &UDebouncedInputComponent::DebouncedUpdate, DebounceDelay, false); | |
// Update the latest value to be processed | |
LastProcessedValue = NewValue; | |
} | |
} | |
void UDebouncedInputComponent::DebouncedUpdate() | |
{ | |
// Broadcast the debounced value | |
OnDebouncedValueChanged.Broadcast(LastProcessedValue); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "CoreMinimal.h" | |
#include "Components/ActorComponent.h" | |
#include "DebouncedInputComponent.generated.h" | |
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnDebouncedValueChanged, float, Value); | |
UCLASS(ClassGroup=(Custom), meta=(BlueprintSpawnableComponent)) | |
class YOURPROJECT_API UDebouncedInputComponent : public UActorComponent | |
{ | |
GENERATED_BODY() | |
public: | |
UDebouncedInputComponent(); | |
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Debounce Settings") | |
float DebounceDelay; | |
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Debounce Settings") | |
float Threshold; | |
UPROPERTY(BlueprintAssignable, Category="Debounce") | |
FOnDebouncedValueChanged OnDebouncedValueChanged; | |
// Call this function to update the value and apply debounce logic | |
void UpdateValue(float NewValue); | |
protected: | |
virtual void BeginPlay() override; | |
private: | |
UPROPERTY() | |
float LastProcessedValue; | |
FTimerHandle DebounceTimerHandle; | |
void DebouncedUpdate(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment