0
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ I suggest to avoid all pixel calculation until you're about to draw. Is 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\$ – Vaillancourt Jan 15 '16 at 18:05
  • \$\begingroup\$ Yep I think I need the length of the vector, how would I find that? \$\endgroup\$ – Zac G Jan 15 '16 at 18:07
3
\$\begingroup\$

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 your speed as calculated above is already in m/s and you're done. :)

  • velocity = (10px, 0, 0) then your speed as calculated above is in px/s, and you'll need to divide by pixelsPerMeter value (10, as described in the question) in order to convert it into m/s

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Works perfectly - I can't accept for 1 minute so I'll do that when I can! \$\endgroup\$ – Zac G Jan 15 '16 at 18:10
  • \$\begingroup\$ @ZacG Glad to hear it's working for you! I'm in no rush. ;) \$\endgroup\$ – DMGregory Jan 15 '16 at 18:11
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.