Monday, March 13, 2017

Introduction to programming in Unreal Engine 4 part 2

If you followed my previous post about programming in Unreal Engine you surely has created a camera and static mesh component, that are attached to root component. Now we are gonna "learn our character to move and jump".

1. We will need to change input settings in unreal editor, so go to "Edit" and then "Project Settings",
2. Now go to "Engine" and "Input",
 3. And set "Bindings" like on the picture.

First of all let's create few variables and functions in our header file:

"void Move(float value);
void DoJump();
FVector ActorLocation;
USceneComponent* VisibleComponent;
FVector CurrentVelocity;"

We will need them later.
Now we should declare our input in SetupInputPlayerComponent function. To do so write:

"InputComponent->BindAxis("Move", this, &AMainCharacter::Move);
InputComponent->BindAction("Jump", IE_Pressed, this, &AMainCharacter::DoJump);"

And now our DoJump and Move functions declarations.

"void AMainCharacter::Move(float value)
         CurrentVelocity.X = FMath::Clamp ( value, 1.0f, -1.0f)* 100.0f;
void AMainCharacter::DoJump()
         CurrentVelocity.Z = 1000.0f;

Now comes the most important thing we need to let our player to move over time (every tick).
So let's write in our "Tick" function:

"ActorLocation = GetActorLocation();
           FVector NewLocation = ActorLocation + (CurrentVelocity * DeltaTime);
           SetActorLocation (NewLocation);
if (CurrentVelocity.Z > 0.0f || CurrentVelocity < 0.0f || CurrentVelocity.Z == 0.0f && ActorLocation.Z >=0.0f)
           CurrentVelocity.Z -= 100.0f;
if (ActorLocation.Z <=0.0f)
           CurrentVelocity.Z = 0.0f

  1. Now if we press space the DoJump function will be called and will set our main character's velocity to 1000.
  2. After every tick will lose 100 velocity until it's speed will be bigger than 0.
  3. Then it's velocity will be equal to  0 and and it will be higher than 0 so it will start to get minus velocity and it will start falling.
  4. Then it will still fall because our velocity will be lower than 0.
  5. Until it hits the 0 height (so our ground).

No comments:

Post a Comment