SetThrottle improved for keyboard (wasd)

Hello, this is my SetThrottle logic improved for the keyboard, you can adjust the ForceAdjustment variable to make the Tank move more or less based on the current friction. My current friction on the track is 0.2(min combine mode).

void UTankTrackComponent::SetThrottle(float Throttle)
{
    //TODO: Apply acceleration over time to a maximum value
    //TODO: Limit speed due to dual control

    if (Throttle == 0.0f)
    {
        return;
    }

    Throttle = FMath::Clamp<float>(Throttle, -1.0f, 1.0f);
    float CurrentForceAdjustment = (2.3f / FMath::Abs(Throttle));
    float TankMass = Cast<ATank>(GetOwner())->GetMass();
    float MassRelation = (TankMass >= 1000) ? (TankMass / 1000) : 1;
    float TrackMaxDrivingForce = (TankMass * GravityAcceleration * MassRelation * CurrentForceAdjustment);
    float ThrottleChange = (Throttle * TrackMaxDrivingForce);

    FVector ForceApplied = (GetForwardVector() * ThrottleChange);
    ForceApplied.X = FMath::Clamp<float>(ForceApplied.X, -TrackMaxDrivingForce / CurrentForceAdjustment, TrackMaxDrivingForce / CurrentForceAdjustment);
    ForceApplied.Y = FMath::Clamp<float>(ForceApplied.Y, -TrackMaxDrivingForce / CurrentForceAdjustment, TrackMaxDrivingForce / CurrentForceAdjustment);
    ForceApplied.Z = FMath::Clamp<float>(ForceApplied.Z, -TrackMaxDrivingForce / CurrentForceAdjustment, TrackMaxDrivingForce / CurrentForceAdjustment);

    auto TankRoot = Cast<UPrimitiveComponent>(GetOwner()->GetRootComponent());
    TankRoot->AddForceAtLocation(ForceApplied, GetComponentLocation());
}
void UTankMovementComponent::IntendMoveForward(float Throw)
{
    UE_LOG(LogTemp, Warning, TEXT("IntendMoveForward: %f"), Throw);

    //TODO: Limit speed due to dual control

    TankTrackLeftComponent->SetThrottle(Throw);
    TankTrackRightComponent->SetThrottle(Throw);
}

void UTankMovementComponent::IntendMoveLeft(float Throw)
{
    UE_LOG(LogTemp, Warning, TEXT("IntendMoveLeft: %f"), Throw);

    TankTrackLeftComponent->SetThrottle(-Throw);
    TankTrackRightComponent->SetThrottle(Throw);
}

void UTankMovementComponent::IntendMoveRight(float Throw)
{
    UE_LOG(LogTemp, Warning, TEXT("IntendMoveRight: %f"), Throw);

    TankTrackLeftComponent->SetThrottle(Throw);
    TankTrackRightComponent->SetThrottle(-Throw);
}

void UTankMovementComponent::IntendMoveBackward(float Throw)
{
    UE_LOG(LogTemp, Warning, TEXT("IntendMoveBackward: %f"), Throw);

    TankTrackLeftComponent->SetThrottle(-Throw);
    TankTrackRightComponent->SetThrottle(-Throw);
}
1 Like

Awesome work! C++ isn’t always easy! Kudos to you!

Privacy & Terms