Yes, I can implement wall-running functionality for Sonic when he reaches a certain speed, allowing him to run on walls and maintain his speed to continue wall-running. Additionally, I will adjust Sonic's mesh rotation to correctly align with walls and sloped floors.
Below is the implementation that adds wall-running capabilities and adjusts the mesh rotation accordingly.
1. Define Custom Movement Modes
First, we'll define a custom movement mode for wall-running using an enumeration. Add the following code to your SonicMovementComponent.h file:
// At the top of the .h file, after includes
UENUM(BlueprintType)
enum class ESonicCustomMovementMode : uint8
{
CMOVE_None UMETA(DisplayName = "None"),
CMOVE_WallRunning UMETA(DisplayName = "WallRunning")
};
2. Add Properties and Functions for Wall-Running
In your USonicMovementComponent class, add the following properties and functions:
public:
USonicMovementComponent();
// Override PhysCustom to handle custom movement modes
virtual void PhysCustom(float deltaTime, int32 Iterations) override;
protected:
// Wall-running functions
void StartWallRunning(const FVector& SurfaceNormal);
void StopWallRunning();
void PhysWallRunning(float deltaTime, int32 Iterations);
// Helper functions
bool CanWallRunOnSurface(const FVector& SurfaceNormal) const;
bool IsWallRunning() const;
// Wall-running properties
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement | Wall Running")
float WallRunMinSpeed;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement | Wall Running")
float WallRunGravityScale;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement | Wall Running")
float MaxWallRunTime;
// Store the time Sonic has been on the wall
float WallRunTime;
// The normal of the wall we're running on
FVector WallRunSurfaceNormal;
3. Initialize Wall-Running Properties
In your USonicMovementComponent constructor, initialize the wall-running properties:
USonicMovementComponent::USonicMovementComponent()
{
// ... existing code ...
WallRunMinSpeed = 500.0f; // Adjust as needed
WallRunGravityScale = 0.5f; // Reduce gravity during wall run
MaxWallRunTime = 10.0f; // Maximum time Sonic can wall-run
WallRunTime = 0.0f;
// ... existing code ...
}
4. Override PhysCustom Function
Override the PhysCustom function to handle custom movement modes:
void USonicMovementComponent::PhysCustom(float deltaTime, int32 Iterations)
{
if (CustomMovementMode == static_cast<uint8>(ESonicCustomMovementMode::CMOVE_WallRunning))
{
PhysWallRunning(deltaTime, Iterations);
}
else
{
Super::PhysCustom(deltaTime, Iterations);
}
}
5. Implement Wall-Running Physics
Implement the PhysWallRunning function to handle the wall-running behavior:
void USonicMovementComponent::PhysWallRunning(float deltaTime, int32 Iterations)
{
if (deltaTime < MIN_TICK_TIME)
{
return;
}
// Increment wall run time
WallRunTime += deltaTime;
// Check if wall run time has exceeded maximum allowed time
if (WallRunTime >= MaxWallRunTime)
{
StopWallRunning();
return;
}
// Apply reduced gravity during wall run
FVector Gravity = FVector(0.0f, 0.0f, GetGravityZ() * WallRunGravityScale);
Velocity += Gravity * deltaTime;
// Move along the wall surface
FVector WallRight = FVector::CrossProduct(FVector::UpVector, WallRunSurfaceNormal).GetSafeNormal();
FVector AdjustedVelocity = FVector::VectorPlaneProject(Velocity, WallRunSurfaceNormal);
// Move the character
MoveUpdatedComponent(AdjustedVelocity * deltaTime, UpdatedComponent->GetComponentQuat(), true);
// Ensure the character maintains the minimum wall-running speed
float CurrentSpeed = Velocity.Size();
if (CurrentSpeed < WallRunMinSpeed)
{
StopWallRunning();
return;
}
// Check if Sonic is still in contact with the wall
FHitResult HitResult;
FVector Start = UpdatedComponent->GetComponentLocation();
FVector End = Start - WallRunSurfaceNormal * 100.0f; // Adjust distance as needed
FCollisionQueryParams QueryParams;
QueryParams.AddIgnoredActor(GetOwner());
bool bHit = GetWorld()->LineTraceSingleByChannel(HitResult, Start, End, ECC_Visibility, QueryParams);
if (!bHit || !CanWallRunOnSurface(HitResult.ImpactNormal))
{
// Sonic is no longer able to wall-run
StopWallRunning();
}
else
{
// Update the wall normal
WallRunSurfaceNormal = HitResult.ImpactNormal;
// Rotate Sonic to align with the wall
FRotator TargetRotation = FRotationMatrix::MakeFromZX(-WallRunSurfaceNormal, GetOwner()->GetActorForwardVector()).Rotator();
FRotator NewRotation = FMath::RInterpTo(GetOwner()->GetActorRotation(), TargetRotation, deltaTime, RotationInterpSpeed);
GetOwner()->SetActorRotation(NewRotation);
}
}
6. Implement Wall-Running Start and Stop Functions
Implement the StartWallRunning and StopWallRunning functions:
void USonicMovementComponent::StartWallRunning(const FVector& SurfaceNormal)
{
WallRunSurfaceNormal = SurfaceNormal;
WallRunTime = 0.0f;
SetMovementMode(MOVE_Custom, static_cast<uint8>(ESonicCustomMovementMode::CMOVE_WallRunning));
GravityScale = WallRunGravityScale;
}
void USonicMovementComponent::StopWallRunning()
{
SetMovementMode(MOVE_Falling);
GravityScale = 1.0f;
}
7. Check If Sonic Can Wall-Run on a Surface
Implement the CanWallRunOnSurface function to determine if a wall is suitable for wall-running:
bool USonicMovementComponent::CanWallRunOnSurface(const FVector& SurfaceNormal) const
{
// Allow wall-running on surfaces that are approximately vertical
float VerticalDot = FVector::DotProduct(SurfaceNormal, FVector::UpVector);
return VerticalDot < 0.1f && VerticalDot > -0.1f; // Adjust tolerance as needed
}
8. Implement IsWallRunning Function
Implement the IsWallRunning function to check if Sonic is currently wall-running:
bool USonicMovementComponent::IsWallRunning() const
{
return MovementMode == MOVE_Custom && CustomMovementMode == static_cast<uint8>(ESonicCustomMovementMode::CMOVE_WallRunning);
}
9. Check for Wall-Running in TickComponent
In the TickComponent function, check if Sonic meets the conditions to start wall-running:
void USonicMovementComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ... existing code ...
// Check for wall-running initiation
if (!IsWallRunning() && IsFalling())
{
// Check if Sonic is moving fast enough
if (GetVelocity().Size() >= WallRunMinSpeed)
{
// Perform a line trace to check for a wall
FVector Start = GetActorLocation();
FVector ForwardDir = GetActorForwardVector();
FVector End = Start + ForwardDir * 100.0f; // Adjust distance as needed
FHitResult HitResult;
FCollisionQueryParams QueryParams;
QueryParams.AddIgnoredActor(GetOwner());
bool bHit = GetWorld()->LineTraceSingleByChannel(HitResult, Start, End, ECC_Visibility, QueryParams);
// Check if we hit a suitable wall surface
if (bHit && CanWallRunOnSurface(HitResult.ImpactNormal))
{
// Start wall-running
StartWallRunning(HitResult.ImpactNormal);
}
}
}
}
10. Adjust Mesh Rotation on Sloped Floors
Override the PhysWalking function to adjust Sonic's mesh rotation based on the floor's normal:
void USonicMovementComponent::PhysWalking(float deltaTime, int32 Iterations)
{
Super::PhysWalking(deltaTime, Iterations);
if (!CharacterOwner)
{
return;
}
// Adjust character rotation to align with floor normal
const FFindFloorResult& Floor = CurrentFloor;
if (Floor.IsWalkableFloor())
{
FVector FloorNormal = Floor.HitResult.ImpactNormal;
FVector Forward = GetOwner()->GetActorForwardVector();
FRotator TargetRotation = FRotationMatrix::MakeFromZX(FloorNormal, Forward).Rotator();
// Interpolate rotation for smoothness
FRotator NewRotation = FMath::RInterpTo(GetOwner()->GetActorRotation(), TargetRotation, deltaTime, RotationInterpSpeed);
GetOwner()->SetActorRotation(NewRotation);
}
}
11. Adjust Mesh Rotation While Falling
Override the PhysFalling function to adjust Sonic's rotation based on movement direction:
void USonicMovementComponent::PhysFalling(float deltaTime, int32 Iterations)
{
Super::PhysFalling(deltaTime, Iterations);
if (!CharacterOwner)
{
return;
}
// Adjust character rotation based on velocity direction
FVector CurrentVelocity = Velocity;
if (!CurrentVelocity.IsNearlyZero())
{
FRotator TargetRotation = CurrentVelocity.Rotation();
FRotator CurrentRotation = GetOwner()->GetActorRotation();
// Keep pitch and roll the same
TargetRotation.Pitch = CurrentRotation.Pitch;
TargetRotation.Roll = CurrentRotation.Roll;
FRotator NewRotation = FMath::RInterpTo(CurrentRotation, TargetRotation, deltaTime, RotationInterpSpeed);
GetOwner()->SetActorRotation(NewRotation);
}
}
12. Handle Transitions and Safety Checks
Ensure that transitions between wall-running, walking, and falling are smooth and that all safety checks are in place. This includes resetting gravity scale and movement modes appropriately.
Additional Notes
- Adjust the properties such as
WallRunMinSpeed, WallRunGravityScale, and MaxWallRunTime based on your game's requirements.
- Ensure that
RotationInterpSpeed is set to a value that provides smooth rotation transitions.
- You might need to tweak collision settings to ensure that Sonic doesn't get stuck or clip through walls during wall-running.
Conclusion
By implementing the above code, Sonic will be able to run on walls when moving fast enough, and his mesh will correctly rotate based on wall and floor normals. This enhances the gameplay experience by allowing dynamic movement and realistic character orientation.
Remember to test thoroughly to ensure that the wall-running feels smooth and natural and that there are no unexpected behaviors or bugs. Adjust the parameters and logic as necessary to fit your game's mechanics and desired player experience.