How to do Delay in C++

So i am new to c++, i made a system where an actor goes in a direction and returns back to the original place in tick function, my code is like this


What i want to do is set a delay of a 1 or 2 sec at the start of “else” but i dont have any idea how to do it, can someone help me pls.

And also i must make its condition as a bool, otherwise every bp i made from this will stop which i dont want

The way you do this in C++ is to use timers. There are some examples here:

In your header, add a couple members. They don’t need to be properties. I think something like this should work. I’m guessing you have a platform that goes back and forth.

float MovePlatformDelay = 2.0f; // Set delay in seconds here.
float MovePlatformTimer = -1.0f;
void AMovingPlatform::MovePlatform(float DeltaTime)
{
  if (ShouldPlatformReturn())
  {
    FVector MoveDirection = PlatformVelocity.GetSafeNormal();
    StartLocation = StartLocation + MoveDirection * MoveDistance;
    SetActorLocation(StartLocation);
    PlatformVelocity = -PlatformVelocity;
    MovePlatformTimer = MovePlatformDelay;
  }
  else if (MovePlatformTimer > 0.0f)
  {
    MovePlatformTimer -= DeltaTime;
  }
  else
  {
    FVector CurrentLocation = GetActorLocation();
    CurrentLocation = CurrentLocation + PlatformVelocity * DeltaTime;
    SetActorLocation(CurrentLocation);
  }
}

You can use timers or just use a couple floats like above since you’re already using the Tick function.

1 Like