# How to get the Javascript equivalent of GameMaker's hspeed and vspeed given only direction and speed?

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 {
};
}


### 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 {
};
}

• I intend to give you best answer, I just want to test it first. May 21 '19 at 19:53
• @CocoDaWhiteBerry did it work? May 21 '19 at 21:24
• I got it to work with some modifications, which I've posted as my own answer to this question. May 22 '19 at 5:26

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;
}