Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

// Fill out your copyright notice in the Description page of Project Settings. #pragma…

  1. User

    // Fill out your copyright notice in the Description page of Project Settings.

    #pragma once

    #include "CoreMinimal.h" #include "MovementSplineActor.h" #include "GameFramework/CharacterMovementComponent.h" #include "SonicMovementComponent.generated.h"

    class ASonicCharacterComponent;

    /**

    • Custom movement component for Sonic character */ UCLASS() class SONICUNLEASHEDREMAKE_API USonicMovementComponent : public UCharacterMovementComponent { GENERATED_BODY()

    public: USonicMovementComponent();

    void CrouchMovementHandler();
    virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
    virtual void InitializeComponent() override;
    virtual void BeginPlay() override;
    void OnLanded();
    
    // Movement functions
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    void MoveForward(float Value);
    
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    void MoveRight(float Value);
    
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    void Jump();
    
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    float GetForwardSpeed() const;
    
    
    
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    void LaunchSonic(float Speed, FVector Direction, float OutOfControlTime, float KeepVelocityTime,
        bool bAlignToMovementDirection, float HomingCooldown, bool bCanHomingAttackAfterLaunch = true,
        bool bCanAirDashAfterLaunch = true, bool bMaintainMomentum = false);
    
    
    // Control functions
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
    void GoOutOfControl(float Duration);
    
    void DoStomp();
    void DoUnleashedStomp();
    void DoGenerationsStomp();
    void DoCrouchedMovement();
    void DoSlide();
    void StopSlide();
    bool HighEnoughToStomp();
    bool IsSonicSliding();
    bool IsSonicCrouching();
    bool IsSonicStomping();
    //crouch stuff
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
        void RightFaceButtonPressed();
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
        void RightFaceButtonReleased();
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
        void EnableStomp();
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
        void DisableStomp();
    UFUNCTION(BlueprintCallable, Category = "Sonic Movement")
        bool IsStompEnabled();
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement")
    float SplineInfluenceSpeedThreshold;
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement")
    float SplineInfluenceRadius;
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement")
    float SplineNudgingForce;
    
    AMovementSplineActor* CurrentSplineActor;
    void HandleSplines();
    

    protected: // Helper functions bool bCanStomp;

    float CalculateLateralMovementScale(float Speed) const;
    void ApplyLateralMovement();
    void DisableCharacterControls();
    void EnableCharacterControls();
    void UpdateCharacterRotation(float DeltaTime);
    
    // Timer handle
    FTimerHandle OutOfControlTimerHandle;
    
    // Character reference
    UPROPERTY()
    ASonicCharacterComponent* SonicCharacter;
    
    // Movement properties
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float MaxBoostSpeed;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float BoostAcceleration;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float LateralMovementScale;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float MinLateralMovementScale;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float MinTurnRadius;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float MaxTurnRadius;
    
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Sonic Movement")
    bool bIsOutOfControl;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float RotationInterpSpeed;
    
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Sonic Movement", meta = (ClampMin = "0"))
    float MinSpeedForMaxTurnRadius;
    
    // Generations stomp will stop all movement and move you down
    // Unleashed stomp will keep your current momentum so send you down and still move you forward
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stomp", meta = (ClampMin = "0"))
        bool UnleashedStomp;
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Stomp", meta = (ClampMin = "0"))
        float StompPower;
    

    };

    // Fill out your copyright notice in the Description page of Project Settings.

    #include "Sonic/SonicMovementComponent.h" #include "Sonic/ESonicCharacterState.h" #include "Sonic/HelperFunctions.h" #include "Sonic/SonicCharacterComponent.h" #include "GameFramework/PlayerController.h" #include "Kismet/GameplayStatics.h" #include "Kismet/KismetMathLibrary.h"

    USonicMovementComponent::USonicMovementComponent() { MaxBoostSpeed = 9000.0f; BoostAcceleration = 2000.0f; MaxWalkSpeed = 6000.0f; MinLateralMovementScale = 0.1f; LateralMovementScale = 1.0f; bIsOutOfControl = false; MinTurnRadius = 10.0f; MaxTurnRadius = 100.0f; RotationInterpSpeed = 10.0f; MinSpeedForMaxTurnRadius = 5000.0f; SplineInfluenceSpeedThreshold = 5000.0f; SplineInfluenceRadius = 750.0f; SplineNudgingForce = 0.2f; }

    void USonicMovementComponent::CrouchMovementHandler() { if (SonicCharacter->CurrentState == EFEeSonicCharacterState::Sliding) { if (SonicCharacter->GetVelocity().Size() < 1) { StopSlide(); return; } if (IsFalling()) StopSlide(); } if (SonicCharacter->CurrentState == EFEeSonicCharacterState::Crouch) { if (SonicCharacter->GetVelocity().Size() > 1) { SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling; } } }

    void USonicMovementComponent::InitializeComponent() { Super::InitializeComponent();

    // Initialize Sonic-specific movement parameters
    GravityScale = 4.0f;
    MaxAcceleration = 1000.0f;
    BrakingFrictionFactor = 0.05f;
    SetWalkableFloorAngle(60.0f);
    MaxWalkSpeed = 6000.0f;
    GroundFriction = 8.75f;
    JumpZVelocity = 800.0f;
    AirControl = 0.8f;
    BrakingDecelerationFalling = 0.2f;
    AirControlBoostMultiplier = 1.0f;
    FallingLateralFriction = 4.0f;
    MaxFlySpeed = 7000.0f;
    BrakingDecelerationFlying = 1750.0f;
    MaxCustomMovementSpeed = 9000.0f;
    RotationRate = FRotator(0.0f, 540.0f, 0.0f);
    bCanStomp = true;
    UnleashedStomp = true;
    StompPower = 2000.0f;
    

    }

    void USonicMovementComponent::BeginPlay() { Super::BeginPlay(); SonicCharacter = Cast(GetOwner()); }

    void USonicMovementComponent::OnLanded() { SonicCharacter->BoostComponent->EnableAirBoosting(); SonicCharacter->HomingAttackComponent->AirDashEnable(); EnableStomp(); if (SonicCharacter->CurrentState == EFEeSonicCharacterState::WallJumping || SonicCharacter->CurrentState == EFEeSonicCharacterState::Stomping) SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling;

    }

    void USonicMovementComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); ApplyLateralMovement(); UpdateCharacterRotation(DeltaTime); CrouchMovementHandler(); HandleSplines(); }

    //Calculate the lateral movement scale based on current speed, this will limit the influence of lateral input. float USonicMovementComponent::CalculateLateralMovementScale(float Speed) const { float MaxSpeed = MaxWalkSpeed; float Scale = 1.0f - (Speed / MaxSpeed); return FMath::Clamp(Scale, MinLateralMovementScale, 1.0f); }

    void USonicMovementComponent::ApplyLateralMovement() { if (SonicCharacter) { float CurrentSpeed = SonicCharacter->GetVelocity().Size2D(); LateralMovementScale = CalculateLateralMovementScale(CurrentSpeed); } }

    void USonicMovementComponent::MoveForward(float Value) { if (!SonicCharacter || bIsOutOfControl || !SonicCharacter->bCanMove) return; if (IsSonicSliding() || IsSonicCrouching() || IsSonicStomping()) Value = 0; const FRotator Rotation = SonicCharacter->SonicCameraComponent->GetCurrentlyActiveCamera()->GetActorRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); SonicCharacter->AddMovementInput(Direction, Value); }

    void USonicMovementComponent::MoveRight(float Value) { if (!SonicCharacter || bIsOutOfControl || !SonicCharacter->bCanMove) return; if (IsSonicSliding() || IsSonicCrouching()) Value = 0; const FRotator Rotation = SonicCharacter->SonicCameraComponent->GetCurrentlyActiveCamera()->GetActorRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); SonicCharacter->AddMovementInput(Direction, Value); }

    void USonicMovementComponent::UpdateCharacterRotation(float DeltaTime) { if (!SonicCharacter) return;

    FVector CurrentVelocity = SonicCharacter->GetVelocity();
    float Speed = CurrentVelocity.Size2D();
    
    if (Speed > 0.1f)
    {
        // Calculate the target rotation based on velocity
        FRotator TargetRotation = CurrentVelocity.Rotation();
    
        // Calculate the turn radius based on speed
        float SpeedRatio = FMath::Clamp(Speed / MinSpeedForMaxTurnRadius, 0.0f, 1.0f);
        float CurrentTurnRadius = FMath::Lerp(MinTurnRadius, MaxTurnRadius, SpeedRatio);
    
        // Adjust the rotation rate based on the turn radius
        float CurrentRotationRate = 360.0f / (2 * PI * CurrentTurnRadius);
        RotationRate = FRotator(0.0f, CurrentRotationRate, 0.0f);
    
        // Interpolate the current rotation to the target rotation
        FRotator NewRotation = FMath::RInterpTo(SonicCharacter->GetActorRotation(), TargetRotation, DeltaTime, RotationInterpSpeed);
    
        // Set the new rotation
        SonicCharacter->SetActorRotation(NewRotation);
    }
    

    }

    void USonicMovementComponent::GoOutOfControl(float Duration) { if (Duration <= 0.0f) return;

    bIsOutOfControl = true; 
    DisableCharacterControls();
    GetWorld()->GetTimerManager().SetTimer(OutOfControlTimerHandle, this, &USonicMovementComponent::EnableCharacterControls, Duration, false);
    

    }

    void USonicMovementComponent::DoStomp() { SonicCharacter->CurrentState = EFEeSonicCharacterState::Stomping; DisableStomp(); UnleashedStomp ? DoUnleashedStomp() : DoGenerationsStomp(); }

    void USonicMovementComponent::DoUnleashedStomp() { Velocity = SonicCharacter->GetVelocity()/2; FVector StompDirection = FVector(0.0f, 0.0f, -1.0f) * StompPower; AddImpulse(StompDirection, true); }

    void USonicMovementComponent::DoGenerationsStomp() { Velocity = FVector::ZeroVector; FVector StompDirection = FVector(0.0f, 0.0f, -1.0f) * StompPower; AddImpulse(StompDirection, true); }

    void USonicMovementComponent::DoCrouchedMovement() { if (!SonicCharacter) return; if (SonicCharacter->GetVelocity().Size() > 1) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("DoSlide")); DoSlide(); } else { SonicCharacter->CurrentState = EFEeSonicCharacterState::Crouch; } }

    void USonicMovementComponent::DoSlide() { SonicCharacter->CurrentState = EFEeSonicCharacterState::Sliding; }

    void USonicMovementComponent::StopSlide() { SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling; }

    bool USonicMovementComponent::HighEnoughToStomp() { float searchDistance = 1000.0f; float distance = HelperFunctions::GetDistanceFromGround(GetWorld(), SonicCharacter->GetActorLocation(), searchDistance); GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("Distance from ground: %f"), distance)); return distance > 30.0f; }

    bool USonicMovementComponent::IsSonicSliding() { return SonicCharacter->CurrentState == EFEeSonicCharacterState::Sliding; }

    bool USonicMovementComponent::IsSonicCrouching() { return SonicCharacter->CurrentState == EFEeSonicCharacterState::Crouch; }

    bool USonicMovementComponent::IsSonicStomping() { return SonicCharacter->CurrentState == EFEeSonicCharacterState::Stomping; }

    void USonicMovementComponent::RightFaceButtonPressed() { if (!SonicCharacter) return; if (IsFalling() && IsStompEnabled() && HighEnoughToStomp()) { DoStomp(); return; } if (!IsFalling()) DoCrouchedMovement(); }

    void USonicMovementComponent::RightFaceButtonReleased() { if (!SonicCharacter) return; if (SonicCharacter->CurrentState == EFEeSonicCharacterState::Crouch) { SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling; } }

    void USonicMovementComponent::EnableStomp() { bCanStomp = true; }

    void USonicMovementComponent::DisableStomp() { bCanStomp = false; }

    bool USonicMovementComponent::IsStompEnabled() { return bCanStomp; }

    void USonicMovementComponent::HandleSplines() { UWorld* World = GetWorld(); if (!World) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, TEXT("World is null!")); return; }

    TArray<AActor*> FoundActors;
    UGameplayStatics::GetAllActorsOfClass(World, AMovementSplineActor::StaticClass(), FoundActors);
    FVector PlayerLocation = SonicCharacter->GetActorLocation();
    float ClosestDistance = FLT_MAX;
    FVector DesiredFindLocation = PlayerLocation + (SonicCharacter->GetActorForwardVector() * 200.0f);
    if (FoundActors.Num() == 0)
    {
        CurrentSplineActor = nullptr;
        return;
    }
    for (AActor* FoundActor : FoundActors)
    {
        AMovementSplineActor* SplineActor = Cast<AMovementSplineActor>(FoundActor);
        if (SplineActor)
        {
            FVector SplineLocation = SplineActor->SplineComponent->FindLocationClosestToWorldLocation(DesiredFindLocation, ESplineCoordinateSpace::World);
            float Distance = FVector::Dist(PlayerLocation, SplineLocation);
            if (Distance < ClosestDistance)
            {
                ClosestDistance = Distance;
                CurrentSplineActor = SplineActor;
            }
        }
    }
    // we need to get the forward input to check if the user is holding the stick
    float forwardInput = SonicCharacter->GetInputAxisValue("MoveForward");
    float rightInput = SonicCharacter->GetInputAxisValue("MoveRight");
    float totalInput = FMath::Abs(forwardInput) + FMath::Abs(rightInput);
    
    if (totalInput < 0.1f && !SonicCharacter->BoostComponent->IsBoosting())
    {
        CurrentSplineActor = nullptr;
    }
    if (CurrentSplineActor && SonicCharacter->CurrentState == EFEeSonicCharacterState::MovingOnGround)
    {
        float ForwardDistance = 200.0f;
        FVector ForwardVector = SonicCharacter->GetActorForwardVector() * ForwardDistance;
        FVector DesiredLocation = PlayerLocation + ForwardVector;
        FVector Location = CurrentSplineActor->SplineComponent->FindLocationClosestToWorldLocation(DesiredLocation, ESplineCoordinateSpace::World);
        FRotator DesiredRotation = (Location - PlayerLocation).GetSafeNormal().Rotation();
        DesiredRotation.Pitch = 0.0f;
        SonicCharacter->FancyArrow->SetWorldRotation(DesiredRotation);
    
        float DotProduct = FVector::DotProduct(SonicCharacter->GetActorForwardVector(), (Location - PlayerLocation).GetSafeNormal());
        if (DotProduct < 0.0f)
        {
            CurrentSplineActor = nullptr;
            return;
        }
        FVector DesiredDirection = (Location - PlayerLocation).GetSafeNormal();
        float DistanceToSpline = FVector::Dist(SonicCharacter->GetActorLocation(), Location);
        float SpeedInfluence = FMath::Clamp(SonicCharacter->GetVelocity().Size() / SplineInfluenceSpeedThreshold, 0.0f, 1.0f );
        float SplineWeight = FMath::Clamp((1.0f - DistanceToSpline / SplineInfluenceRadius) * SpeedInfluence, 0.0f, 1.0f);
    
        FVector MovementDirection = SonicCharacter->GetActorForwardVector();
        FVector BlendedDirection = FMath::Lerp(MovementDirection, DesiredDirection, SplineWeight).GetSafeNormal();
        
        SonicCharacter->AddMovementInput(BlendedDirection, SplineNudgingForce * SplineWeight);
        
    }
    

    }

    void USonicMovementComponent::DisableCharacterControls() { if (APlayerController* PlayerController = GetWorld()->GetFirstPlayerController()) { SonicCharacter->DisableInput(PlayerController); } }

    void USonicMovementComponent::EnableCharacterControls() { if (APlayerController* PlayerController = GetWorld()->GetFirstPlayerController()) { SonicCharacter->EnableInput(PlayerController); } bIsOutOfControl = false; }

    void USonicMovementComponent::Jump() { if (!SonicCharacter) return; const FVector JumpDirection = SonicCharacter->GetActorUpVector() * JumpZVelocity; AddImpulse(JumpDirection, true); SonicCharacter->CurrentState = EFEeSonicCharacterState::Jumping; }

    float USonicMovementComponent::GetForwardSpeed() const { FVector Velo = Velocity; Velo.Z = 0.0f; return Velo.Size(); }

    void USonicMovementComponent::LaunchSonic(float Speed, FVector Direction, float OutOfControlTime, float KeepVelocityTime, bool bAlignToMovementDirection, float HomingCooldown, bool bCanHomingAttackAfterLaunch, bool bCanAirDashAfterLaunch, bool bMaintainMomentum) { if (!SonicCharacter) { UE_LOG(LogTemp, Error, TEXT("SonicMovementComponent: SonicCharacter is not set!")); return; }

    const FVector LaunchVelocity = Direction * Speed;
    if (LaunchVelocity.Z > 0.0f)
    {
        SetMovementMode(MOVE_Falling);
        SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling;
    }
    
    if (!bMaintainMomentum)
    {
        Velocity = FVector::ZeroVector;
    }
    Velocity += LaunchVelocity;
    
    if (bAlignToMovementDirection)
    {
        FRotator LaunchRotation = LaunchVelocity.Rotation();
        LaunchRotation.Pitch = SonicCharacter->GetActorRotation().Pitch;
        LaunchRotation.Roll = SonicCharacter->GetActorRotation().Roll;
        SonicCharacter->SetActorRotation(LaunchRotation);
    }
    
    // Handle component-specific logic
    if (bCanAirDashAfterLaunch)
    {
        SonicCharacter->HomingAttackComponent->AirDashEnable();
    }
    if (bCanHomingAttackAfterLaunch)
    {
        SonicCharacter->HomingAttackComponent->HomingAttackEnable();
    }
    if (HomingCooldown > 0.0f)
    {
        SonicCharacter->HomingAttackComponent->HomingAttackCooldownEnable(HomingCooldown);
    }
    if (OutOfControlTime > 0.0f)
    {
        GoOutOfControl(OutOfControlTime);
    }
    
    // Debug message
    GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("LaunchSonic: Speed=%f, Direction=(%f, %f, %f)"), Speed, Direction.X, Direction.Y, Direction.Z));
    

    }

    so... right now yes the movement works on a flat surface, but sonic can move omnidirectionally when he is going fast enough, so when he moves fast enough he can run on walls and ceiligs and basically anything. Please try to implement this, i want a 1 size fits all solution, when you jump off the wall you disingage the wall or ceilig. when you move too slow you also disengage, please help me implement this because i want sonic to move smoothly within loopdieloops and tubes

  2. Assistant

    Implementing omni-directional movement for Sonic, allowing him to run on walls and ceilings when moving fast enough, involves enhancing your existing USonicMovementComponent. The goal is to dynamically adjust Sonic's orientation, gravity, and movement based on the surfaces around him and his current speed. Below is a comprehensive guide to achieve this functionality.


    1. Overview of the Approach

    1. Surface Detection: Continuously detect the surfaces around Sonic using collision checks (e.g., ray casts or sphere overlaps) to determine potential walls or ceilings to run on.

    2. State Management: Introduce a new movement state, such as RunningOnSurface, to handle transitions between normal ground movement and surface running.

    3. Adjust Gravity and Orientation: Modify gravity direction and alter Sonic's orientation to align with the detected surface normal when running on walls or ceilings.

    4. Movement Adaptation: Adapt movement controls to allow Sonic to navigate smoothly along the detected surface.

    5. Disengagement Conditions: Implement conditions to disengage surface running, such as jumping, reducing speed below a threshold, or moving away from the surface.


    2. Extending the Movement Component

    2.1. Update the Character State Enum

    First, extend your character state enumeration to include a new state for surface running.

    // EFEeSonicCharacterState.h
    
    UENUM(BlueprintType)
    enum class EFEeSonicCharacterState : uint8
    {
        MovingOnGround UMETA(DisplayName = "Moving On Ground"),
        Jumping        UMETA(DisplayName = "Jumping"),
        Falling        UMETA(DisplayName = "Falling"),
        Stomping       UMETA(DisplayName = "Stomping"),
        Sliding        UMETA(DisplayName = "Sliding"),
        Crouch         UMETA(DisplayName = "Crouch"),
        RunningOnSurface UMETA(DisplayName = "Running On Surface")
    };
    

    2.2. Add New Variables to Handle Surface Running

    In your USonicMovementComponent class, add the necessary variables to manage surface running.

    // SonicMovementComponent.h
    
    protected:
        // Surface Running Variables
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float SurfaceRunSpeedThreshold; // Minimum speed to engage surface running
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float SurfaceDetectionDistance; // Distance to detect potential surfaces
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float GravityScaleNormal; // Normal gravity scale
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float GravityScaleSurface; // Adjusted gravity when running on a surface
    
        FHitResult CurrentSurfaceHit; // Information about the current surface
    
        bool bIsRunningOnSurface; // Flag to indicate surface running state
    
        // Helper function to detect surfaces
        bool DetectSurface(FHitResult& OutHit);
    

    2.3. Initialize Variables in the Constructor

    Set default values for the new variables in the constructor.

    // SonicMovementComponent.cpp
    
    USonicMovementComponent::USonicMovementComponent()
    {
        // Existing initializations...
    
        // Surface Running Initializations
        SurfaceRunSpeedThreshold = 5000.0f; // Example value, adjust as needed
        SurfaceDetectionDistance = 150.0f;
        GravityScaleNormal = 4.0f;
        GravityScaleSurface = 2.0f; // Reduced gravity when on surface
        bIsRunningOnSurface = false;
    }
    

    2.4. Implement Surface Detection

    Create the DetectSurface function to check for nearby surfaces suitable for running.

    // SonicMovementComponent.cpp
    
    bool USonicMovementComponent::DetectSurface(FHitResult& OutHit)
    {
        FVector Start = SonicCharacter->GetActorLocation();
        FVector ForwardVector = SonicCharacter->GetActorForwardVector();
        FVector RightVector = SonicCharacter->GetActorRightVector();
    
        // Define multiple rays around Sonic to detect surfaces (front, back, left, right)
        TArray<FVector> RayDirections = {
            ForwardVector,
            -ForwardVector,
            RightVector,
            -RightVector
        };
    
        for (const FVector& Direction : RayDirections)
        {
            FVector End = Start + Direction * SurfaceDetectionDistance;
            FCollisionQueryParams QueryParams;
            QueryParams.AddIgnoredActor(SonicCharacter);
    
            if (GetWorld()->LineTraceSingleByChannel(OutHit, Start, End, ECC_WorldStatic, QueryParams))
            {
                // Check if the surface normal is within acceptable range (not too steep)
                float DotProduct = FVector::DotProduct(OutHit.Normal, FVector::UpVector);
                // Accept surfaces that are roughly vertical (e.g., walls, ceilings)
                if (FMath::Abs(DotProduct) < 0.5f) // Adjust the angle threshold as needed
                {
                    return true;
                }
            }
        }
    
        return false;
    }
    

    2.5. Modify the TickComponent to Handle Surface Running

    Enhance the TickComponent function to manage surface running based on detected surfaces and speed.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
    {
        Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
    
        ApplyLateralMovement();
        UpdateCharacterRotation(DeltaTime);
        CrouchMovementHandler();
        HandleSplines();
    
        HandleSurfaceRunning(DeltaTime);
    }
    

    2.6. Implement HandleSurfaceRunning Function

    Create a new function to handle the logic for engaging and disengaging surface running.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::HandleSurfaceRunning(float DeltaTime)
    {
        if (!SonicCharacter) return;
    
        FVector CurrentVelocity2D = SonicCharacter->GetVelocity();
        CurrentVelocity2D.Z = 0.0f;
        float CurrentSpeed = CurrentVelocity2D.Size();
    
        // Check if speed is above the threshold
        if (CurrentSpeed >= SurfaceRunSpeedThreshold)
        {
            FHitResult SurfaceHit;
            if (DetectSurface(SurfaceHit))
            {
                // If not already running on a surface, engage surface running
                if (!bIsRunningOnSurface)
                {
                    EngageSurfaceRunning(SurfaceHit);
                }
                else
                {
                    // If already on a surface, update the surface if needed
                    // For smooth transitions, you may want to interpolate towards the new surface
                    CurrentSurfaceHit = SurfaceHit;
                    AlignWithSurface(SurfaceHit.Normal, DeltaTime);
                    AdjustGravityForSurface(SurfaceHit.Normal);
                }
                return;
            }
        }
    
        // If conditions to engage surface running are not met, disengage
        if (bIsRunningOnSurface)
        {
            DisengageSurfaceRunning();
        }
    }
    

    2.7. Implement EngageSurfaceRunning Function

    Define how to engage surface running when a suitable surface is detected.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::EngageSurfaceRunning(const FHitResult& SurfaceHit)
    {
        bIsRunningOnSurface = true;
        CurrentSurfaceHit = SurfaceHit;
    
        // Adjust gravity to align with the new surface
        AdjustGravityForSurface(SurfaceHit.Normal);
    
        // Align character's rotation with the surface normal
        AlignWithSurface(SurfaceHit.Normal, 0.0f);
    
        // Change the character's state
        SonicCharacter->CurrentState = EFEeSonicCharacterState::RunningOnSurface;
    
        // Optionally reduce or modify velocity based on surface
        // For example, project velocity onto the surface
        Velocity = FVector::VectorPlaneProject(Velocity, SurfaceHit.Normal);
    }
    

    2.8. Implement AdjustGravityForSurface Function

    Modify the gravity direction based on the surface normal.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::AdjustGravityForSurface(const FVector& SurfaceNormal)
    {
        // Calculate the new gravity direction opposite to the surface normal
        FVector NewGravity = -SurfaceNormal.GetSafeNormal();
    
        // Set gravity scale based on surface running
        GravityScale = GravityScaleSurface;
    
        // Apply a custom gravity vector if needed
        // This might require overriding the gravity direction in the movement component
        // UCharacterMovementComponent doesn't support changing gravity direction directly
        // So, you can simulate it by adjusting the actor's rotation and applying forces accordingly
    
        // Optionally rotate the world or the character to align with the surface
        // For simplicity, we'll adjust the character's rotation
        FRotator NewRotation = SurfaceNormal.Rotation();
        SonicCharacter->SetActorRotation(NewRotation);
    }
    

    Note: Unreal Engine's UCharacterMovementComponent does not natively support altering the gravity direction. To achieve a custom gravity direction, consider applying a force opposite to the desired gravity or manipulating the character's rotation and movement accordingly. For a more advanced setup, you might need to override certain movement functions or use a custom physics solution.

    2.9. Implement AlignWithSurface Function

    Ensure Sonic's orientation aligns smoothly with the surface.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::AlignWithSurface(const FVector& SurfaceNormal, float DeltaTime)
    {
        if (!SonicCharacter) return;
    
        // Calculate the desired rotation based on the surface normal
        FRotator DesiredRotation = SurfaceNormal.Rotation();
        DesiredRotation.Pitch = 0.0f; // Keep pitch level if desired
    
        // Interpolate to the desired rotation for smoothness
        FRotator NewRotation = FMath::RInterpTo(SonicCharacter->GetActorRotation(), DesiredRotation, DeltaTime, RotationInterpSpeed);
        SonicCharacter->SetActorRotation(NewRotation);
    }
    

    2.10. Implement DisengageSurfaceRunning Function

    Define how to exit surface running mode when conditions are no longer met.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::DisengageSurfaceRunning()
    {
        bIsRunningOnSurface = false;
    
        // Reset gravity scale to normal
        GravityScale = GravityScaleNormal;
    
        // Reset the character's rotation if needed
        // Optionally, interpolate back to the default rotation
        // For simplicity, assume the character should face forward on the ground
        FRotator DesiredRotation = FRotator(0.0f, SonicCharacter->GetActorRotation().Yaw, 0.0f);
        FRotator NewRotation = FMath::RInterpTo(SonicCharacter->GetActorRotation(), DesiredRotation, GetWorld()->GetDeltaSeconds(), RotationInterpSpeed);
        SonicCharacter->SetActorRotation(NewRotation);
    
        // Change the character's state
        SonicCharacter->CurrentState = EFEeSonicCharacterState::Falling;
    }
    

    2.11. Handle Disengagement Conditions

    Ensure Sonic disengages from surface running when he jumps or slows down.

    2.11.1. Modify the Jump Function

    Override the Jump function to ensure that jumping discontinues surface running.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::Jump()
    {
        if (!SonicCharacter) return;
    
        Super::Jump(); // Call the base jump functionality
    
        if (bIsRunningOnSurface)
        {
            DisengageSurfaceRunning();
        }
    
        // Additional jump logic if necessary
    }
    

    2.11.2. Modify the MoveForward and MoveRight Functions

    Ensure that movement input affects surface running appropriately and disengages it when necessary.

    // SonicMovementComponent.cpp
    
    void USonicMovementComponent::MoveForward(float Value)
    {
        if (!SonicCharacter || bIsOutOfControl || !SonicCharacter->bCanMove) return;
        if (IsSonicSliding() || IsSonicCrouching() || IsSonicStomping()) Value = 0;
    
        if (bIsRunningOnSurface)
        {
            // Move along the surface
            FVector Direction = FVector::VectorPlaneProject(SonicCharacter->GetActorForwardVector(), CurrentSurfaceHit.Normal).GetSafeNormal();
            SonicCharacter->AddMovementInput(Direction, Value);
            return;
        }
    
        // Existing ground movement logic
        const FRotator Rotation = SonicCharacter->SonicCameraComponent->GetCurrentlyActiveCamera()->GetActorRotation();
        const FRotator YawRotation(0, Rotation.Yaw, 0);
        const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
        SonicCharacter->AddMovementInput(Direction, Value);
    }
    
    void USonicMovementComponent::MoveRight(float Value)
    {
        if (!SonicCharacter || bIsOutOfControl || !SonicCharacter->bCanMove) return;
        if (IsSonicSliding() || IsSonicCrouching()) Value = 0;
    
        if (bIsRunningOnSurface)
        {
            // Move along the surface
            FVector Direction = FVector::VectorPlaneProject(SonicCharacter->GetActorRightVector(), CurrentSurfaceHit.Normal).GetSafeNormal();
            SonicCharacter->AddMovementInput(Direction, Value);
            return;
        }
    
        // Existing ground movement logic
        const FRotator Rotation = SonicCharacter->SonicCameraComponent->GetCurrentlyActiveCamera()->GetActorRotation();
        const FRotator YawRotation(0, Rotation.Yaw, 0);
        const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
        SonicCharacter->AddMovementInput(Direction, Value);
    }
    

    2.12. Update Movement Parameters for Surface Running

    Adjust movement parameters such as friction, acceleration, and velocity to suit surface running.

    // In EngageSurfaceRunning and DisengageSurfaceRunning, adjust movement properties as needed.
    
    void USonicMovementComponent::EngageSurfaceRunning(const FHitResult& SurfaceHit)
    {
        // Existing code...
    
        // Modify movement properties for surface running
        Friction = 2.0f; // Increased friction to prevent sliding off surfaces
        MaxWalkSpeed = 6000.0f; // Adjust speed if necessary
        AirControl = 0.5f; // Reduced air control when on surfaces
    }
    
    void USonicMovementComponent::DisengageSurfaceRunning()
    {
        // Existing code...
    
        // Reset movement properties to normal
        Friction = 8.75f;
        MaxWalkSpeed = 6000.0f;
        AirControl = 0.8f;
    }
    

    3. Additional Considerations

    3.1. Smooth Transitions

    To ensure smooth transitions between different movement states (e.g., ground to wall, wall to ceiling), interpolate rotations and adjust physics forces gradually.

    3.2. Camera Adjustments

    Depending on how your camera is set up, you might need to adjust the camera's orientation to match Sonic's new orientation when running on surfaces.

    3.3. Animation Handling

    Ensure that your character's animations respond correctly to the new movement state. You might need to introduce new animations or adjust existing ones for surface running.

    3.4. Edge Cases and Testing

    Thoroughly test edge cases, such as transitions between multiple surfaces, rapid speed changes, and interactions with different geometry (loops, tubes, etc.) to ensure robust behavior.


    4. Complete Code Integration

    Integrate the above methods into your SonicMovementComponent.cpp as shown. Below is a consolidated view of the new additions and modifications:

    SonicMovementComponent.h

    #pragma once
    
    #include "CoreMinimal.h"
    #include "MovementSplineActor.h"
    #include "GameFramework/CharacterMovementComponent.h"
    #include "SonicMovementComponent.generated.h"
    
    class ASonicCharacterComponent;
    
    /**
     * Custom movement component for Sonic character
     */
    UCLASS()
    class SONICUNLEASHEDREMAKE_API USonicMovementComponent : public UCharacterMovementComponent
    {
        GENERATED_BODY()
        
    public:
        USonicMovementComponent();
    
        // Existing functions...
    
        // Surface Running functions
        void HandleSurfaceRunning(float DeltaTime);
        void EngageSurfaceRunning(const FHitResult& SurfaceHit);
        void DisengageSurfaceRunning();
        bool DetectSurface(FHitResult& OutHit);
        void AdjustGravityForSurface(const FVector& SurfaceNormal);
        void AlignWithSurface(const FVector& SurfaceNormal, float DeltaTime);
    
    protected:
        // Existing variables...
    
        // Surface Running Variables
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float SurfaceRunSpeedThreshold; // Minimum speed to engage surface running
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float SurfaceDetectionDistance; // Distance to detect potential surfaces
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float GravityScaleNormal; // Normal gravity scale
    
        UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Surface Running")
        float GravityScaleSurface; // Adjusted gravity when running on a surface
    
        FHitResult CurrentSurfaceHit; // Information about the current surface
    
        bool bIsRunningOnSurface; // Flag to indicate surface running state
    };
    

    SonicMovementComponent.cpp

    #include "Sonic/SonicMovementComponent.h"
    #include "Sonic/ESonicCharacterState.h"
    #include "Sonic/HelperFunctions.h"
    #include "Sonic/SonicCharacterComponent.h"
    #include "GameFramework/PlayerController.h"
    #include "Kismet/GameplayStatics.h"
    #include "Kismet/UKismetMathLibrary.h"
    
    // Constructor Initialization
    USonicMovementComponent::USonicMovementComponent()
    {
        // Existing initializations...
    
        // Surface Running Initializations
        SurfaceRunSpeedThreshold = 5000.0f; // Example value, adjust as needed
        SurfaceDetectionDistance = 150.0f;
        GravityScaleNormal = 4.0f;
        GravityScaleSurface = 2.0f; // Reduced gravity when on surface
        bIsRunningOnSurface = false;
    }
    
    // Existing functions...
    
    bool USonicMovementComponent::DetectSurface(FHitResult& OutHit)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::HandleSurfaceRunning(float DeltaTime)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::EngageSurfaceRunning(const FHitResult& SurfaceHit)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::AdjustGravityForSurface(const FVector& SurfaceNormal)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::AlignWithSurface(const FVector& SurfaceNormal, float DeltaTime)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::DisengageSurfaceRunning()
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
    {
        Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
    
        ApplyLateralMovement();
        UpdateCharacterRotation(DeltaTime);
        CrouchMovementHandler();
        HandleSplines();
    
        HandleSurfaceRunning(DeltaTime);
    }
    
    // Override Jump to disengage surface running
    void USonicMovementComponent::Jump()
    {
        if (!SonicCharacter) return;
    
        Super::Jump(); // Call the base jump functionality
    
        if (bIsRunningOnSurface)
        {
            DisengageSurfaceRunning();
        }
    
        // Additional jump logic if necessary
    }
    
    // Modify movement functions to handle surface running
    void USonicMovementComponent::MoveForward(float Value)
    {
        // Implementation as shown above
    }
    
    void USonicMovementComponent::MoveRight(float Value)
    {
        // Implementation as shown above
    }
    

    5. Final Notes

    Implementing omni-directional movement with surface running involves significant changes to the movement logic and state management. Ensure that you:

    • Test Extensively: Verify the functionality across various surfaces, speeds, and edge cases to ensure a smooth gameplay experience.

    • Optimize Performance: Surface detection can be computationally expensive. Optimize ray casts or collision checks to minimize performance impacts, possibly by limiting checks to essential frames or regions.

    • Enhance User Feedback: Provide visual or audio cues when transitioning between movement states to inform players of the change in control dynamics.

    By carefully integrating these changes, you can achieve the desired omni-directional movement for Sonic, enabling him to traverse complex environments like loop-de-loops and tubes with fluidity and responsiveness.