1
\$\begingroup\$

I'm using a NodeJS server to control NPC movement in a multiplayer game, and when they get too close to the edge of the room I need to reverse either the horizontal or vertical components of their velocities (how to decide which, is a bridge I'll cross when I get there).

The problem is I already have their direction and speed, and am able to convert it to hspeed and vspeed, but not back again.

I need the inverse of this function:

function velocityToSpeeds(direction, speed) {
  return {
    x: -speed*Math.sin(Math.toRad(direction - 90)), 
    y: -speed*Math.cos(Math.toRad(direction - 90))
  };
}
\$\endgroup\$
1
\$\begingroup\$

You want to convert cartesian coordinates to polar.

Use Math.atan2(vy, vx) to get direction (it's in radians).
For velocity magnitude, use Math.sqrt(vx*vx+vy*vy).

vx and vy are your horizontal and vertical components of speed.

Also

Your existing code can be simplified.

function velocityToSpeeds(direction, speed) {
  return {
    x: speed*Math.cos(Math.toRad(direction)), 
    y: speed*Math.sin(Math.toRad(direction))
  };
}
\$\endgroup\$
  • \$\begingroup\$ I intend to give you best answer, I just want to test it first. \$\endgroup\$ – Coco DaWhiteBerry May 21 '19 at 19:53
  • \$\begingroup\$ @CocoDaWhiteBerry did it work? \$\endgroup\$ – trollingchar May 21 '19 at 21:24
  • \$\begingroup\$ I got it to work with some modifications, which I've posted as my own answer to this question. \$\endgroup\$ – Coco DaWhiteBerry May 22 '19 at 5:26
0
\$\begingroup\$

I got it to work with these formulas:

function velocityToSpeeds(direction, speed) {
  return {
    hspeed: Number(-Number(speed)*Math.sin(Math.toRad(Number(direction) - 90))) + 0, 
    vspeed: Number(-Number(speed)*Math.cos(Math.toRad(Number(direction) - 90))) + 0
  };
}

function speedsToVelocity(hspeed, vspeed) {
  return {
    direction: Math.round(Number(Math.toDeg(Math.atan2(Number(vspeed), Number(hspeed))))) + 0,
    speed: Math.round(Number(Math.sqrt(Number(hspeed) * Number(hspeed) + Number(vspeed) * Number(vspeed)))) + 0
  }
}

Here are a couple more as a bonus:

function negativeHspeed(direction) {
  return ((180 - direction) + 360) % 360;
}

function negativeVspeed(direction) {
    return 360 - direction;
}
\$\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.