i am making a 2d game where the character jumps from planet to planet, with that the character does rotate. i want to add velocity when the transform.right velocity.magnitude is < speed. how do you find the magnitude of a velocity the transform.right direction?
The easiest way is to simply inverse transform the velocity vector (which is always in worldspace) into local space by using InverseTransformDirection.
Vector 2 v = transform.InverseTransformDirection(rb.velocity);
where “rb” is your Rigidbody2D. If you use 3d physics you can simply exchange Vector2 with Vector3.
“v.x” will contain the part of the velocity along the objects right axis and “v.y” along the up axis.
If for some reason you can’t use the normal local space of the object, you can still “manually” project the velocity vector onto the right vector by using Vector3.Project.
Vector2 r = Vector3.Project(rb.velocity, transform.right);
The resulting vector “r” is still in world space. It’s the same as using “v.x * transform.right” from the first solution. So “r” also points to the right, but it lenght represents the “right-part” of the velocity. In other words those will both give you the amount of velocity along the right axis:
float amount = v.x; float amount = r.magnitude;
Dont work for me, return 0 from magnitude ??