NebulaGames

C++ to Blueprints Stop Watch Tutorial

Feb 28th, 2019
567
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.08 KB | None | 0 0
  1. // Fill out your copyright notice in the Description page of Project Settings.
  2.  
  3. #pragma once
  4.  
  5. #include "CoreMinimal.h"
  6. #include "Runtime/Engine/Classes/GameFramework/Actor.h"
  7. #include "Components/ActorComponent.h"
  8. #include "Runtime/Engine/Public/TimerManager.h"
  9. #include "StopWatch.generated.h"
  10.  
  11.  
  12. UCLASS( ClassGroup=(Custom), Blueprintable, meta=(BlueprintSpawnableComponent) )
  13. class CODE_TEST_API UStopWatch : public UActorComponent
  14. {
  15.     GENERATED_BODY()
  16.  
  17. public:
  18.  
  19.     UStopWatch();                                                           // Function to set default values for this component's properties
  20.  
  21.     UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stop Watch", meta = (ClampMin = "0", UIMin = "0"))      // Blueprint exposed variable to set "Minutes"
  22.         int32 Start_Minutes;
  23.     UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stop Watch", meta = (ClampMin = "0", ClampMax = "59", UIMin = "0", UIMax = "59"))       // Blueprint exposed variable to set "Seconds"
  24.         int32 Start_Seconds;   
  25.     UPROPERTY(BlueprintReadOnly, Category = "Stop Watch")                       // Blueprint variable "read only" to access "Time Stamp" data
  26.         FString TimeStamp;
  27.     UPROPERTY(BlueprintReadOnly, Category = "Stop Watch")                       // Blueprint variable "read only" to access current Millisecond value
  28.         float Milliseconds;
  29.     UPROPERTY(BlueprintReadOnly, Category = "Stop Watch")                       // Blueprint variable "read only" to access current Seconds value
  30.         float Current_Seconds;
  31.     UPROPERTY(BlueprintReadOnly, Category = "Stop Watch")                       // Blueprint variable "read only" to access current Minutes value
  32.         float Current_Minutes;
  33.  
  34.     UFUNCTION(BlueprintCallable)                                                // Blueprint exposed function to start the StopWatch/Timer
  35.         void Start_Timer(bool StopWatch, float Rate);                           // Rate will be modified to a number that 100 is divisible by
  36.     UFUNCTION(BlueprintCallable)                                                // Blueprint exposed function to pause the StopWatch/Timer
  37.         void Pause();
  38.     UFUNCTION(BlueprintCallable)                                                // Blueprint exposed function to unpause the StopWatch/Timer
  39.         void Unpause();
  40.     UFUNCTION(BlueprintCallable)                                                // Blueprint exposed function to clear the StopWatch/Timer
  41.         void ClearTimer();
  42.     UFUNCTION()
  43.         void StopWatch();                                                      
  44.     UFUNCTION()
  45.         void GenerateTimeStamp();
  46.     UFUNCTION(BlueprintImplementableEvent)                                      // Event scripted in Blueprints to occur when Timer hits "0"
  47.         void Time_Is_Up();                                                      // Call this event using the function name "Time Is Up"
  48.    
  49.  
  50.     bool IsStopWatch;                                                           // Global variable for function access
  51.                        
  52.     float MillisecondsChange;                                                   // Declare necessary variables for StopWatch/Timer functionality
  53.     float MillisecondsReset;
  54.     float MillisecondsResetValue;
  55.     float SecondsChange;
  56.     float SecondsReset;
  57.     float SecondsResetValue;
  58.     float MinutesChange;
  59.  
  60.     FString MinutesOutput;
  61.     FString SecondsOutput;
  62.     FString MillisecondsOutput;
  63.    
  64.     FTimerHandle StopWatchHandle;
  65.  
  66.     AActor* Parent_Actor;
  67.  
  68.     // Called every frame
  69.     virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
  70.  
  71. protected:
  72.     // Called when the game starts
  73.     virtual void BeginPlay() override;
  74.  
  75.        
  76. };
  77.  
  78.  
  79.  
  80.  
  81.  
  82. -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
  83.  
  84.  
  85.  
  86.  
  87.  
  88. #include "StopWatch.h"
  89.  
  90. // Sets default values for this component's properties
  91. UStopWatch::UStopWatch()
  92. {
  93.     PrimaryComponentTick.bCanEverTick = false;              // Disable tick for this component
  94.  
  95.     Milliseconds = 0.f;                                     // Set default variables
  96.  
  97.     Parent_Actor = GetOwner();                              // Retrieve actor component Parent Actor
  98.    
  99. }
  100.  
  101.  
  102. // Called when the game starts
  103. void UStopWatch::BeginPlay()
  104. {
  105.  
  106.     Super::BeginPlay();
  107.    
  108. }
  109.  
  110.  
  111. // Called every frame
  112. void UStopWatch::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
  113. {
  114.  
  115.     Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
  116.  
  117. }
  118.  
  119.  
  120. void UStopWatch::Start_Timer(bool StopWatch, float Rate)
  121. {
  122.     Current_Seconds = float(Start_Seconds);                 // Convert input values to float for calculations (prevents improper input through blueprints)
  123.     Current_Minutes = float(Start_Minutes);
  124.    
  125.     if (Rate == 0)                                          // Prevent division by "0" from improper user input
  126.     {
  127.         Rate = 1;
  128.     }
  129.    
  130.     if (fmod(100, Rate) != 0)                               // Ensure 100 divisible to a whole number by any input rate
  131.     {
  132.         Rate = 5;                                           // Default rate value if impoper value entered
  133.     }
  134.  
  135.     IsStopWatch = StopWatch;                                // Grab input bool from blueprint function call and set global variable
  136.  
  137.     if (IsStopWatch == true)                                // Set values for "additive" time
  138.     {
  139.         Current_Seconds = 0;                                // If "Stop Watch" mode is true, set minutes and seconds to "0" in case this was forgotten
  140.         Current_Minutes = 0;
  141.         MillisecondsChange = Rate;                          // Value matches rate at which timer runs, 0.05 sec timer will (+5) from milliseconds each pass
  142.         SecondsChange = 1.f;
  143.         MinutesChange = 1.f;
  144.         MillisecondsReset = 100.f;
  145.         SecondsReset = 60.f;
  146.         MillisecondsResetValue = 0.f;
  147.         SecondsResetValue = 0.f;
  148.     }
  149.     else                                                    // Set values for "subtractive" time
  150.     {
  151.         MillisecondsChange = -Rate;                         // Value matches rate at which timer runs, 0.05 sec timer will (-5) from milliseconds each pass
  152.         SecondsChange = -1.f;
  153.         MinutesChange = -1.f;
  154.         MillisecondsReset = 0 - Rate;                       // Cosmetic reset value, if reset at "0" Time Stamp would read "00:4:100" going from >5 to 4 seconds                           
  155.         SecondsReset = -1.f;                                // Prefer "00:05:05", "00:05:00", "00:04:95" opposed to "00:05:05", "00:04:100", "00:04:95"    
  156.         MillisecondsResetValue = 100 - Rate;                // Although values are equivalent
  157.         SecondsResetValue = 59.f;
  158.  
  159.         if (Current_Seconds == 0)                           // Only necessary for "Timer-Style" (Subtractive) mode, performs initial subtraction prior to function call
  160.         {
  161.             Current_Minutes += MinutesChange;
  162.             Current_Seconds = SecondsResetValue;
  163.             Milliseconds = MillisecondsResetValue;
  164.         }
  165.         else                                                // If starting value for seconds > 0 simply subtract the first second and add to milliseconds
  166.         {
  167.             Current_Seconds += SecondsChange;
  168.             Milliseconds = MillisecondsResetValue;
  169.         }
  170.     }
  171.    
  172.     Parent_Actor->GetWorldTimerManager().SetTimer(StopWatchHandle, this, &UStopWatch::StopWatch, Rate/100, true);       // Create a timer
  173.  
  174. }
  175.  
  176. void UStopWatch::StopWatch()                            // Function that actually calculates "time"
  177. {
  178.    
  179.     Milliseconds += MillisecondsChange;                     // Add or Subtract 5 from the value of "Milliseconds" each call of this function
  180.  
  181.     if (Milliseconds == MillisecondsReset)                  // If value of "Milliseconds" = the "reset value" add or subtract appropriately from "Seconds"
  182.     {
  183.         Milliseconds = MillisecondsResetValue;         
  184.         Current_Seconds += SecondsChange;
  185.  
  186.         if (Current_Seconds == SecondsReset)                // Check if "Seconds" has reached its reset value and add or subtract from "Minutes" appropriately
  187.         {
  188.             Current_Seconds = SecondsResetValue;
  189.             Current_Minutes += MinutesChange;
  190.         }
  191.        
  192.     }
  193.  
  194.     GenerateTimeStamp();                                    // Function call to create Time Stamp format "00:00:00"
  195.  
  196.     if (IsStopWatch == false && Current_Minutes < 0)        // If using "Timer-Sytle" mode set all values to 0 upon completion and call "Time Is Up" function
  197.     {
  198.        
  199.         Parent_Actor->GetWorldTimerManager().ClearTimer(StopWatchHandle);       // Clear timer handle (prevents timer from continuing to execute)
  200.  
  201.         Current_Minutes = 0;                                // Sets Minutes, Seconds and Milliseconds to default 0,0,0
  202.         Current_Seconds = 0;
  203.         Milliseconds = 0;
  204.  
  205.         GenerateTimeStamp();                                // Create final Time Stamp showing "00:00:00"
  206.  
  207.         Time_Is_Up();                                       // Call to Blueprint Implemented Function (*Allows for custom events to occur when timer reaches "0")
  208.                                                            
  209.     }
  210.    
  211.    
  212. }
  213.  
  214. void UStopWatch::GenerateTimeStamp()                            // Actual function to create a "Time Stamp"
  215. {
  216.  
  217.     MinutesOutput = FString::SanitizeFloat(Current_Minutes, 0);     // Remove trailing 0's from float, only use whole number values
  218.     if (MinutesOutput.Len() < 2)                                    // Add a leading "0" if float is a single digit
  219.     {
  220.         MinutesOutput = "0" + MinutesOutput;
  221.     }
  222.     SecondsOutput = FString::SanitizeFloat(Current_Seconds, 0);
  223.     if (SecondsOutput.Len() < 2)
  224.     {
  225.         SecondsOutput = "0" + SecondsOutput;
  226.     }
  227.     MillisecondsOutput = FString::SanitizeFloat(Milliseconds, 0);
  228.     if (MillisecondsOutput.Len() < 2)
  229.     {
  230.         MillisecondsOutput = "0" + MillisecondsOutput;
  231.     }
  232.  
  233.     TimeStamp = (MinutesOutput + " : " + SecondsOutput + " : " + MillisecondsOutput);       // Add member strings together with separating colons
  234.  
  235. }
  236.  
  237. void UStopWatch::Pause()                                                                // Function to "Pause" timer called from Blueprints
  238. {
  239.     Parent_Actor->GetWorldTimerManager().PauseTimer(StopWatchHandle);
  240. }
  241.  
  242. void UStopWatch::Unpause()                                                          // Function to "Unpause" timer called from Blueprints
  243. {
  244.     Parent_Actor->GetWorldTimerManager().UnPauseTimer(StopWatchHandle);
  245. }
  246.  
  247. void UStopWatch::ClearTimer()                                                           // Function to "Clear" timer called from Blueprints
  248. {
  249.     Parent_Actor->GetWorldTimerManager().ClearTimer(StopWatchHandle);
  250. }
Add Comment
Please, Sign In to add comment