I'm working on a custom character in Unreal Engine 5. I want the player to have his velocity direction based on mouse movement when he is in the air.
For example, when you jump forward and move your mouse right, he should follow the new direction, but if you jump backwards and move your mouse right, it will change direction towards where your back is looking.
UPDATE
I solved it like this:
I created a custom character movement component and overrode CalcVelocity() method:
// AirControl = 0;
// AirControlBoostMultiplier = 0;
// AirControlBoostVelocityThreshold = 0;
// WalkingDirection is a 2D vector that simply defines the direction of movement relative to the camera
// WalkingDirection.X > 0 character moves forward
// WalkingDirection.X < 0 character moves backwards
// WalkingDirection.Y > 0 character moves right
// WalkingDirection.Y < 0 character moves left
// PreviousWalkingDirection is WalkingDirection before jump
void UCustomCharacterMovementComponent::CalcVelocity(float DeltaTime, float Friction, bool bFluid, float BrakingDeceleration)
{
Super::CalcVelocity(DeltaTime, Friction, bFluid, BrakingDeceleration);
// Air control for mouse movement to change direction mid-air after jumping
if (IsMovingOnGround() && !WalkingDirection.IsZero()) {
PreviousWalkingDirection = WalkingDirection;
} else if (!IsMovingOnGround() && !PreviousWalkingDirection.IsZero()) {
FVector VelocityDirection;
if (PreviousWalkingDirection.X != 0 && PreviousWalkingDirection.Y != 0) {
if (PreviousWalkingDirection.X > 0 && PreviousWalkingDirection.Y > 0) {
// Forward and right
VelocityDirection = UpdatedComponent->GetForwardVector() + UpdatedComponent->GetRightVector();
} else if (PreviousWalkingDirection.X > 0 && PreviousWalkingDirection.Y < 0) {
// Forward and left
VelocityDirection = UpdatedComponent->GetForwardVector() - UpdatedComponent->GetRightVector();
} else if (PreviousWalkingDirection.X < 0 && PreviousWalkingDirection.Y > 0) {
// Back and right
VelocityDirection = UpdatedComponent->GetRightVector() - UpdatedComponent->GetForwardVector();
} else if (PreviousWalkingDirection.X < 0 && PreviousWalkingDirection.Y < 0) {
// Back and left
VelocityDirection = -(UpdatedComponent->GetForwardVector() + UpdatedComponent->GetRightVector());
}
VelocityDirection = UKismetMathLibrary::Normal(VelocityDirection / 2);
} else if (PreviousWalkingDirection.X > 0) {
// Forward
VelocityDirection = UpdatedComponent->GetForwardVector();
} else if (PreviousWalkingDirection.X < 0) {
// Back
VelocityDirection = -UpdatedComponent->GetForwardVector();
} else if (PreviousWalkingDirection.Y > 0) {
// Right
VelocityDirection = UpdatedComponent->GetRightVector();
} else if (PreviousWalkingDirection.Y < 0) {
// Left
VelocityDirection = -UpdatedComponent->GetRightVector();
}
Velocity -= Velocity - VelocityDirection * Velocity.Size();
}
}
It works as expected or at least I didn't notice any issues for now. Feel free to use it or suggest improvements.