# Move car at same speed

I want to move car on each game play run with same speed. At present I was getting each time different velocity. I want to fix that.

Here is game play area on which I was moving car:

At present I was moving car in infinite motion without any kind of control. When it collide with wall, it will its direction based on collision calculation.

Here is my source code that I was using to move car:

void Start ()
{
direction = new Vector2 (Random.Range (-1f, 1f), Random.Range (-1f, 1f));
}

void FixedUpdate ()
{

float angle = Mathf.Atan2 (direction.y, direction.x) * Mathf.Rad2Deg;
float targetRot = Mathf.LerpAngle (myRigidbody.rotation, (angle - 90f), 0.1f);
myRigidbody.MoveRotation (targetRot);

myRigidbody.velocity = direction * speed;
//        myRigidbody.MovePosition (myRigidbody.position + direction * Time.deltaTime * speed);

Debug.Log("vel mag: " + myRigidbody.velocity.magnitude);
}

void OnCollisionEnter2D (Collision2D other)
{
ContactPoint2D contact;
contact = other.contacts [0];

//        direction = 2 * (Vector3.Dot(direction, Vector3.Normalize(contact.normal))) * Vector3.Normalize(contact.normal) - direction; //Following formula  v' = 2 * (v . n) * n - v

//        direction *= -1;// Dont know why I had to multiply by -1 but it's inversed otherwisae
Vector2 reflectedVelocity = Vector2.Reflect(direction, contact.normal);
direction = reflectedVelocity;
}


At present on each run of car, I was getting different velocity that I have checked via debug statement. So my target is to move car with same speed always.

• Because your direction is a speed, and you set it to random. Try direction = new Vector2 (Random.Range (-1f, 1f), Random.Range (-1f, 1f)).normalized; (which will screw up if both x and y are 0), – Peter Apr 2 '17 at 17:05
• Yes its just a initial direction giving each time different velocity magnitude during game play. – Siddharth Apr 2 '17 at 17:15

float angle = Random.Range(0f, 2f * Mathf.PI);