Back to portfolio

C++ Movement & Physics Prototype

Status
Completed
Engine
Unreal Engine 4.27
Languages
C++

Problem

Build three first-person mechanics with adjustable movement and object interaction: dash, a gravity gun, and a jetpack.

Ayarlanabilir hareket ve nesne etkileşimi sunan üç birinci şahıs mekaniği geliştirmek: dash, gravity gun ve jetpack.

Approach

Use a Timeline and curve for dash, attachment and physics simulation for held objects, and a boost curve with a flight-time budget for the jetpack.

Dash için Timeline ve eğri; taşınan nesneler için bağlama ve fizik simülasyonu; jetpack için itiş eğrisi ve uçuş süresi sınırı kullanmak.

Result

A playable C++ prototype with source code and separate demos showing how each mechanic behaves.

Kaynak kodu açık, her mekaniğin davranışını ayrı demolarla gösteren oynanabilir bir C++ prototipi.

I built this Unreal Engine 4.27 prototype in C++ for a Junior Game Programmer application. Starting from the first-person template, I implemented dash, a Half-Life-inspired gravity gun, and a jetpack. The scope focuses on gameplay behavior and configurable mechanics rather than visual polish.

Bu prototipi bir Junior Game Programmer başvurusu için Unreal Engine 4.27 ve C++ ile geliştirdim. Birinci şahıs şablonundan başlayarak dash, Half-Life’tan esinlenen gravity gun ve jetpack mekaniklerini uyguladım. Çalışmanın odağı oynanış davranışı ve ayarlanabilir mekanikler; görsel sunum kapsam dışında.

You can review and download this project on GitHub!

Bu projeyi GitHub'da inceleyip indirebilirsin!

The requirement was to propel the player in their current movement direction when the 'Shift' key was pressed. The dash speed and distance needed to be adjustable dynamically.

Benden istenen, 'Shift' tuşuna basıldığında oyuncunun hareket yönüne doğru fırlatılmasıydı. Dash hızının ve mesafesinin dinamik olarak ayarlanabilmesini istediler.

I decided that the most practical way to implement this was to use a Timeline, so I created the variables I needed.

Bunu yapmanın en kullanışlı yolunun Timeline kullanmak olduğuna karar verdim. Bunun için değişkenlerimi oluşturdum.


UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dash", meta=(ClampMin=1, UIMin=1))
float DashSpeed = 200.f;

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Dash", meta=(ClampMin=1, UIMin=1))
float DashDistance = 1000.f;

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Dash")
bool bIsDashing = false;

FVector DashStartLocation;
FVector DashEndLocation;

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Dash")
class UCurveFloat* DashCurve;

FTimeline DashTimeline;

Then I set up the bindings in the BeginPlay() method.

Ardından binding işlemlerini BeginPlay() metodunda yaptım.


// Binding dash functions
if(DashCurve)
{
    FOnTimelineFloat TimelineUpdateCallback;
    FOnTimelineEventStatic TimelineFinishedCallback;
    TimelineUpdateCallback.BindUFunction(this, FName("DashUpdate"));
    TimelineFinishedCallback.BindUFunction(this, FName("DashFinished"));
    DashTimeline.AddInterpFloat(DashCurve, TimelineUpdateCallback);
    DashTimeline.SetTimelineFinishedFunc(TimelineFinishedCallback);
}

else
{
    UE_LOG(LogTemp, Warning, TEXT("DashCurve not assigned in character BP. Please assign it!"));
}

By the way, don't forget to call this function in Tick():

Bu arada, bu fonksiyonu Tick() içinde çağırmayı unutma:


DashTimeline.TickTimeline(DeltaSeconds);

When the 'Shift' key is pressed, the Dash() function is called. It first performs the necessary checks and determines the dash direction. It then calculates the target location using that direction and the specified speed and distance. The duration is calculated from the formula distance = speed * time, and the Timeline's playback rate is adjusted accordingly.

'Shift' tuşuna basıldığında Dash() fonksiyonu çağrılır. Önce bazı gerekli kontroller yapılır ve dash'in yönü belirlenir. Bu yönde, verilen hız ve mesafe bilgilerine göre hedef konum hesaplanır. Süre, mesafe = hız * zaman formülünden bulunur ve Timeline'ın hızı buna göre ayarlanır.


// Dash implementation
void ASTGameProgrammerTaskCharacter::Dash()
{
    if(bIsDashing) return;
    
    if(GetVelocity().Size() <= 0.f) return;

    if(DashCurve == nullptr) return;

    FVector DashDirection = GetVelocity();
    DashDirection.Z = 0.f;
    DashDirection.Normalize();
    
    DashStartLocation = GetActorLocation();
    DashEndLocation = DashStartLocation + DashDirection * DashDistance;
    
    DashTimeline.SetPlayRate(1 / (DashDistance / DashSpeed));
    DashTimeline.PlayFromStart();
    bIsDashing = true;
}

//Function called while running the timeline
void ASTGameProgrammerTaskCharacter::DashUpdate()
{
    const float TimelineValue = DashTimeline.GetPlaybackPosition();
    const float CurveFloatValue = DashCurve->GetFloatValue(TimelineValue);

    const FVector TargetLocation = FMath::Lerp(DashStartLocation, DashEndLocation, CurveFloatValue);
    SetActorLocation(TargetLocation, true);
}

void ASTGameProgrammerTaskCharacter::DashFinished()
{
    bIsDashing = false;
}

Another requested mechanic was a gravity gun like the one in Half-Life: a weapon that lets you pick up objects and throw them around.

Benden istedikleri bir diğer mekanik, Half-Life'taki Gravity Gun'dı. Nesneleri taşıyıp etrafa fırlatabildiğin bir silah.

I need a line trace to select an object to pick up, so I define the necessary variables. I also created a SceneComponent to attach to the weapon mesh, making it easier to set the held object's position.

Taşınacak nesneyi seçmek için Line Trace yapmam gerekecek, bu yüzden ihtiyacım olan değişkenleri tanımlıyorum. Ayrıca taşıyacağım nesnenin nerede duracağını daha kolay belirlemek için silahın mesh'ine bağlayacağım bir SceneComponent oluşturdum.


UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Gravity Gun")
class USceneComponent* GrabbedObjectLocation;

UPROPERTY()
class UPrimitiveComponent* GrabbedObject;

UFUNCTION()
void SetGrabbedObject(UPrimitiveComponent* ObjectToGrab);

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Gravity Gun")
float PickupTraceRange = 5000.f;

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Gravity Gun")
float PickupTraceRadius = 20.f;

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Gravity Gun")
float FiringForce = 5000.f;

//Calling on Left-Mouse-Button press
void OnFire();

// Calling on LMB release
void EndFire();  

FirstPersonCharacter Blueprint
FirstPersonCharacter Blueprint

The logic is simple: trace forward from the camera. If the hit component is simulating physics, disable physics simulation and attach it to the SceneComponent we created.

Mantık çok basit. Kameradan ileriye doğru bir trace gönder. İsabet edilen component fizik simülasyonu kullanıyorsa fiziği kapat ve onu oluşturduğumuz SceneComponent'e bağla.


void ASTGameProgrammerTaskCharacter::OnFire()
{
    const FVector PickupTraceStart = GetFirstPersonCameraComponent()->GetComponentLocation();
    const FVector PickupTraceEnd = PickupTraceStart + GetFirstPersonCameraComponent()->GetForwardVector() * PickupTraceRange;
    FHitResult PickupTraceHitResult;

    const bool bHit = UKismetSystemLibrary::SphereTraceSingle(this, PickupTraceStart, PickupTraceEnd, PickupTraceRadius, UEngineTypes::ConvertToTraceType(ECC_Visibility),
        false, {this}, EDrawDebugTrace::None, PickupTraceHitResult, true);

    if(bHit)
    {
        // If the Hit Component is using physics simulation, we grap it.
        if(UPrimitiveComponent* Prim = PickupTraceHitResult.GetComponent())
        {
            if(Prim->IsSimulatingPhysics())
            {
                SetGrabbedObject(Prim);
            }
        }
    }
}

void ASTGameProgrammerTaskCharacter::SetGrabbedObject(UPrimitiveComponent* ObjectToGrab)
{
    GrabbedObject = ObjectToGrab;
    if(GrabbedObject)
    {
        GrabbedObject->SetSimulatePhysics(false);
        GrabbedObject->AttachToComponent(GrabbedObjectLocation, FAttachmentTransformRules::SnapToTargetNotIncludingScale);
    }
}

Throwing is even simpler than grabbing. Detach the object from the SceneComponent, re-enable physics simulation, and apply a force.

Fırlatmak, tutmaktan da basit. Bağladığımız SceneComponent'ten ayır, fiziği tekrar aç ve kuvvet uygula.


void ASTGameProgrammerTaskCharacter::EndFire()
{
    // Releasing the grabbed object if there is one.
    if(GrabbedObject)
    {
        const FVector ShootVelocity = GetFirstPersonCameraComponent()->GetForwardVector() * FiringForce;

        GrabbedObject->DetachFromComponent(FDetachmentTransformRules::KeepWorldTransform);
        GrabbedObject->SetSimulatePhysics(true);
        GrabbedObject->AddImpulse(ShootVelocity, NAME_None, true);
        SetGrabbedObject(nullptr);
    }
}

For the final task, I had to choose and implement a mechanic from a list. I chose the jetpack because I thought it would work well with the dash mechanic.

Son görev olarak, bir listeden bir mekanik seçip yapmamı istediler. Dash ile uyumlu olacağını düşündüğüm için jetpack'i seçtim.

Holding down the 'Space' key while airborne activates the jetpack, allowing you to hover for two seconds. Havadayken 'Space' tuşunu basılı tutarsan jetpack devreye girer ve 2 saniye boyunca havada süzülmeni sağlar.

UPROPERTY(EditAnywhere, BlueprintReadOnly, Category="Jetpack")
float JetpackMaxTime = 2.f;

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Jetpack")
float JetpackTime = JetpackMaxTime;

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Jetpack")
float JetpackBoostForce = 120.f;

UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category="Jetpack")
bool bIsJetpackActive = false;

UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category="Jetpack")
class UCurveFloat* JetpackBoostCurve;

void ToggleJetpack(const bool bReset, const bool bActivate);
void UpdateJetpack(const float DeltaSeconds);

Jetpack boost curve
Jetpack Boost Curve

When the 'Space' key is pressed, I either jump or activate the jetpack, depending on the current movement mode.

'Space' tuşuna basıldığında, hareket moduna göre zıplıyorum ya da jetpack'i açıyorum.


void ASTGameProgrammerTaskCharacter::JumpButtonPressed()
{
    if(GetCharacterMovement())
    {
        switch (GetCharacterMovement()->MovementMode)
        {
        case EMovementMode::MOVE_Falling:
            ToggleJetpack(false, true);
        case EMovementMode::MOVE_Walking:
            Jump();
        default: ;
        }
    
    }
}

void ASTGameProgrammerTaskCharacter::JumpButtonReleased()
{
    StopJumping();
    ToggleJetpack(false, false);
}

I activate and deactivate the jetpack in ToggleJetpack(). When the bReset parameter is true, it resets the available flight time, which you can think of as refueling. While the jetpack is active, I increase Air Control.

Jetpack'i 'ToggleJetpack()' fonksiyonunda açıp kapatıyorum. 'bReset' parametresi true ise bunu yakıt doldurmak gibi düşünebilirsin. Jetpack açıksa Air Control'ü artırıyorum.


void ASTGameProgrammerTaskCharacter::ToggleJetpack(const bool bReset, const bool bActivate)
{
    if(bReset)
    {
        JetpackTime = JetpackMaxTime;
    }

    bIsJetpackActive = bActivate;

    if(GetCharacterMovement())
    {
        GetCharacterMovement()->AirControl = bIsJetpackActive ? 5.f : 1.f;
    }
}

The logic is straightforward. Each frame, we check whether the jetpack is active by calling UpdateJetpack() in Tick() (that call isn't shown here). If it is active, we apply a force to the character along the Z axis based on the curve and decrease JetpackTime. When the character touches the ground, we reset the available flight time to its maximum.

Çalışma mantığı zor değil. Her frame'de jetpack'in kullanılıp kullanılmadığını kontrol ediyoruz (burada gösterilmeyen UpdateJetpack() çağrısını Tick fonksiyonunda yaparak). Kullanılıyorsa curve'e göre karaktere Z ekseninde kuvvet uyguluyor ve JetpackTime'ı azaltıyoruz. Karakter yere değdiğinde süreyi tekrar maksimuma eşitliyoruz.


void ASTGameProgrammerTaskCharacter::UpdateJetpack(const float DeltaSeconds)
{
    if(bIsJetpackActive)
    {
        JetpackTime -= DeltaSeconds;

        if(JetpackBoostCurve)
        {
            const float BoostAmount = JetpackBoostCurve->GetFloatValue(UKismetMathLibrary::NormalizeToRange(JetpackMaxTime - JetpackTime, 0.f, JetpackMaxTime)) * JetpackBoostForce;
            LaunchCharacter(FVector(0.f, 0.f, BoostAmount), false, true);
        }

        else
        {
            UE_LOG(LogTemp, Warning, TEXT("JetpackBoostCurve is not assigned in character BP!"));
        }

        if(JetpackTime <= 0.f)
        {
            ToggleJetpack(false, false);
        }
        
    }
}


void ASTGameProgrammerTaskCharacter::Landed(const FHitResult& Hit)
{
    Super::Landed(Hit);

    ToggleJetpack(true, false);
}

Back to portfolio