I have a variable called velocity
which I get from a dynamic body in Box2D. It is the velocity of a pirate ship and when I add torque to the ship I want that to be proportional to the speed (m/s - 10px = 1m). My problem is that I can't divide/multiply a float (proportionalTorque
) by the Vector2 quantity of the velocity so what I need is a way of getting the speed (m/s) from the velocity or if there's any other way of multiplying a float by a vector that'd be useful too.
2 Answers
Sounds like you're looking for the vector magnitude, also called (depending on context) its length, Euclidean norm, or Pythagorean Theorem.
ie. speed = sqrt(dot(velocity, velocity));
As Alexandre Vaillancourt points out, in libGDX the len()
method does exactly this. Other environments will almost always have an equivalent (eg. in Unity it's .magnitude
)
The units of this speed are the same as the units of your velocity, so if going 1 m/s along the x-axis is represented as...
velocity = (1m, 0, 0)
then yourspeed
as calculated above is already in m/s and you're done. :)velocity = (10px, 0, 0)
then yourspeed
as calculated above is in px/s, and you'll need to divide bypixelsPerMeter
value (10, as described in the question) in order to convert it into m/s
Generally, when using a vector2 to represent velocity, the length of the vector is the speed, while the coordinates represent the orientation (the direction of the speed).
To extract the length of your velocity
vector, use the .len()
method of your vector:
float speed = velocity.len();
This is described in the doc.
velocity
a vector? If so, generally the speed is the length of the vector while the 2 coordinates are the orientation. So you'd need only to get the length to get the actual speed. If not, your question should be improved to make it more clear what you need. \$\endgroup\$