Apply force over time

Hey everyone,

I’m trying to apply a force over time on my RigidBody, like in “Apply a force of X to my car over a time of 500ms”.

Now I want to chain mutliple of these commands together to preprogram the path my car will go.

Here’s my approach:

void FixedUpdate () {
		long time = (long)(Time.realtimeSinceStartup * 1000);

		if (command != null) {
			if (command.StartTime < time && command.Duration > time - command.StartTime) {
				rb.AddForce (command.Direction * command.Force);
			} else {
				command = null;
			}
		}
	}

Command has 4 properties.

  • StartTime: After how many milliseconds to start applying force
  • Duration: For how many milliseconds to apply the force
  • Dircetion: Vector3 which represents the direction of the force
  • Force: The force to apply

Essentially this works “Okay”, the car will follow a similar path everytime I start the game. My problem is I need the car to follow the exact path everytime I start the game.

I think I’ve got a timing problem, so that sometimes some commands are cancelled just a frame to early or late.
Although my game is really light on physics calculations right now, which is why I thought the interval in which FixedUpdate() is called should be the same every time.

I already tried multiplying the force by Time.deltaTime to adjust for the time it took to to complete the last frame. Subjectively I the result is a little better, but not as consistent as I’d like it to be.

I think one solution would be to use a counter in FixedUpdate and use it’s value as a measure of time, instead of Time.realtimeSinceStartup. But I’d really like have those parameters in ms instead of physics steps.

We’re going with a compromis now:

Commands will be made with a precision of 20ms. So instead of using Time.realtimeSinceStartup to determine if I have to add a force, I’ll use a counter which will increment everytime FixedUpdate() is called. I’ll then multiply the counter by 20 and check the value against my commands.

This way I should get reproducable results.