how to find velocity magnitude relative to transform.right. 2D
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?
Answer by Bunny83 · Feb 28, 2016 at 05:22 AM
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;
Answer by pareinjeanphilippe · Oct 19, 2016 at 09:19 AM
Dont work for me, return 0 from magnitude ??
Your answer
Follow this Question
Related Questions
Adding velocity to an object in a brick breaker game 0 Answers
Trying to add force to an object... is this done correctly? 0 Answers
Climbing code problem (2d physic). 0 Answers
2D Top-Down Shooting Script Errors 1 Answer
Player randomly stops moving 1 Answer