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:

enter image description here

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.

  • 1
    \$\begingroup\$ 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), \$\endgroup\$
    – Peter
    Apr 2 '17 at 17:05
  • \$\begingroup\$ Yes its just a initial direction giving each time different velocity magnitude during game play. \$\endgroup\$
    – Siddharth
    Apr 2 '17 at 17:15

Try replacing your random direction with

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

This will ensure the direction always has unit length, avoiding the singularity where both x & y get a random value of 0. It also selects directions with uniform probability, compared to normalizing a random value in a square, which is biased toward the diagonals of the square.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.