- Home /
Question by
siddharth3322 · Apr 02, 2017 at 04:35 PM ·
rigidbody2dvelocitymoveposition
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.
screen-shot-2017-04-02-at-100057-pm.png
(31.7 kB)
Comment