- Home /
 
How to keep the velocity of a rigidbody2d while changing its direction according to rotation?
For the last few days I've been trying to have a rigidbody2d rotate while keeping its current velocity only changing where the velocity is directed. After some research, this is what I've come up with:
             var v:float;
             v = rigidbody2D.velocity.magnitude;
            
            var cos=Mathf.Cos(gameObject.rigidbody2D.rotation);
            var sin=Mathf.Sin(gameObject.rigidbody2D.rotation);
            
            var unitvector : Vector2;
            unitvector = Vector2(cos,sin);
            unitvector=unitvector.normalized;
            
            var x : float;
            var y : float;
            
            x=unitvector.x;
            y=unitvector.y;
            
            gameObject.rigidbody2D.velocity=Vector2(x*v,y*v);   
 
               However, this only makes the object stand still in the air slighty wiggling back and forth when I press the key. What's wrong with my solution and how can I fix it?
how are you rotating your rigidbody? If you know that a specific axis of the rigidbody should always be the direction of the speed then you could do (assu$$anonymous$$g you want it to go forward):
 v = rigidbody2D.velocity.magnitude;
 //apply some sort of rotation
 rigidbody2D.velocity = transform.forward*v; //change this from forward if something else should be
 
                 I'm rotating it with addtorque. Using up ins$$anonymous$$d of forward (since it's 2D space) this actually works perfectly and is obviously way simpler than what I tried to do. Thank you!
Answer by robertbu · Aug 17, 2014 at 03:45 PM
If you want to keep the velocity constant no matter what direction it is facing or turning, add the following line in FixedUpdate():
  rigidbody2D.velocity.magnitude = rigidbody2D.velocity.magnitude.normalized * someSpeed;
 
              Your answer