# Accelleration and Stopping

I have two “Marker” gameobjects - these are simply to mark the starting point and end point.

Let’s say StartMarker is at 0,0,0 and EndMarker is at 100,0,0. I am using the Generic Car unity project to help setup a basic car with wheelcolliders etc.

I have a Math problem - I want to be able to control the acceleration, not the position of the object. E.g. when object is stationary, accel is 0 - when the game starts, I want this number to increase to a certain level, lets say 10. With a bit of distance calculations (between the car and the stop marker) and 1 - sqrt distance, I have the car slowly accelerating to 10 as it gets closer to it. BUT, Of course, I want to car to STOP are the stop marker, not accelerate to it.

How could I make the calculations do the following:

Accel starts at 0;
Accel slowly increases to MAX_ACCEL (10). At this point, the car should be roughly halfway between the StartMarker and the StopMarker.
Accel goes back down to 0;
As the car will over shoot now - the acceleration isn’t changing. So, Accel needs to drop to -MAX_ACCEL.
When the car is within an acceptable distance of StopMarker. Velocity needs to be countered to stop. So, Accel = -Velocity;

It sounds much simpler in my head, but maybe I’m over complicating it. I know I could interpolate between the positions and slowly moving the car, but I’m more curious as whether this can be done and the maths behind it.

You are talking about acceleration, but I really thing you are talking about velocity. That is you want it to start slow, move the fastest at the middle, and stop at the end. Varying the velocity bassed on a Sine function might be what you are looking for. You are probably better off simulating this rather than using the physics engine. But assuming no other forces including gravity impact the object, you can assign directly Rigidbody.velocity based on distance between the two points. Here is a bit of code:

``````#pragma strict

var start : Transform;
var end   : Transform;

var maxVelocity = 6.0;

private var dir : Vector3;
private var maxDist : float;

function Start () {
dir = end.position - start.position;
maxDist = dir.magnitude;
dir.Normalize();
transform.position = start.position + dir * 0.001;
}

function FixedUpdate() {
var curDist = (transform.position - start.position).magnitude;
if (curDist >= maxDist) {
rigidbody.velocity = Vector3.zero;
}
else {
rigidbody.velocity = dir * maxVelocity * Mathf.Sin(Mathf.PI * curDist/maxDist);
}
}
``````