How to add forces framerate independently?

So, recently I have been working on a racing game with semi realistic physics. I had the car being accelerated by calling the AddForce() function every frame when the player wanted the car to move. That worked fine at start, but when testing the car movement with different framerates, I noticed that the car would reach much greater distances in a determined time with lower framerates, the highest distance was reached with 30fps since the default Max Physics Delta Time is 1/30. Anyhow, since I didn’t want people to play the game with 30fps to gain an advantage, I started thinking for a solution and ended up having a code like this:

void AEpicCar::MoveForward(float Value)	// yes the name of the car class is EpicCar
{
	if (Value == 0.0f)
		return;

	// all the "speed" variables are floats
	this->ForwardSpeedOneTickBefore = this->ForwardSpeed;	// caching the current speed for later use
	this->ForwardSpeed += Value * this->MaxMovementSpeed * GetWorld()->GetDeltaSeconds();	// increasing the value of ForwardSpeed so the car will accelerate
}

void AEpicCar::Tick(float DeltaSeconds)
{
	Super::Tick(DeltaSeconds);
	
	// calculating the exact amount the car should've moved during the latest frame
	// by averaging the current speed multiplied by DeltaTime and the last frame's speed multiplied by DeltaTime
	AddActorLocalOffset(GetActorForwardVector() * (this->ForwardSpeed* DeltaSeconds * 0.5f + this->ForwardSpeedOneTickBefore * DeltaSeconds * 0.5f));
}

Now, I could just use that code and do all the other physics stuff my self, but that would be a lot of work. So the question is:

Is there any way to to add forces framerate independently with the Unreal Engine physics API? And if not, why aren’t they calculating accelerating movements like I did? It just feels like I am missing something very obvious here. And please note that I am not a physics expert by any means so what I am doing might not make any sense.

Ok, I have done some more testing and it just looks like, no matter how hard you try, the UPrimitiveComponent::AddForce function can never be framerate independent for some reason. So to have a framerate independently accelerating car (or any object) that still uses the physics engine in UE, you must use the UPrimitiveComponent::SetPhysicsLinearVelocity with the bAddToCurrent (a parameter of the function) set to true.

And if there is something wrong in using the SetPhysicsLinearVelocity or use have better ways to implement all this, please let me know.

1 Like