Search code examples
c++actorunreal-engine4

Unreal Engine 4 C++ - How to make an actor move up and down along the Z axis


I am new to the Unreal 4 engine and I'm struggling with some things concerning the coding part as I want an actor to move down and up as soon as it reaches a certain height. Here's what I've done so far:

void APickup::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
    FVector NewLocation = GetActorLocation();
    NewLocation.Z += (DeltaTime * 20.f);
    SetActorLocation(NewLocation);
}

I don't get how I can make this work whether with an "If" statement or a "bool" statement. Any help would be much appreciated. Thank you!

Update: The actor stops at a certain height and doesn't move, I need it to go down now. Here's the code:

if(NewLocation.Z <300)
{
    NewLocation.Z +=(DeltaTime * 100.f);
    SetActorLocation(NewLocation);

Solution

  • I guess your question is more related to how to do things in C++ than Unreal Engine itself.

    Using if statements you can check whether you are above certain height or below. However, if you want to have your actor moving up and down you'll need to keep some sort of inner state. Add for instance a bool member variable to keep track of this. In your class declaration (.h file)

    class APickup {
      // ...other things...
    
      bool bImGoingUp = true;
    };
    

    Then in your Tick function check whether you are going up or down and update your height accordingly. Here you need to check too if you are above or below your Z range, and change your moving direction if so. Say you want to move between [-50, 50] (btw, Unreal uses always centimeters)

    void APickup::Tick(float DeltaTime)
    {
      Super::Tick(DeltaTime);
      FVector NewLocation = GetActorLocation();
      if (NewLocation.Z > 50.0f) {
        bImGoingUp = false;
      } else if (NewLocation.Z < -50.0f) {
        bImGoingUp = true;
      }
      float factor = (bImGoingUp ? 20.f : -20.f);
      NewLocation.Z += factor * DeltaTime;
      SetActorLocation(NewLocation);
    }
    

    You also need to make sure your actor starts the game within this range or might ended up going up or down forever.

    This is just a basic example, if you want to make it really robust you'll need to elaborate a bit more your logic. You could too for instance look at your actor's direction of movement to see if you are moving up or down instead of using a boolean.