[0, 0] is top left. 0 degrees is to the right, 270 is straight down.
I refer to angle as “direction”, magnitude as “speed”, and the horizontal and vertical components as “hspeed” and “vspeed”, respectively.
I have tried these 3 functions but they are all glitchy:
function velocityToSpeeds(direction, speed) {
return {
hspeed: Math.round(Number(-Number(speed)*Math.sin(Math.toRad(Number(direction) - 90)))) + 0,
vspeed: Math.round(Number(-Number(speed)*Math.cos(Math.toRad(Number(direction) - 90)))) + 0
};
}
function velocityToSpeedsALTERNATIVE(direction, speed) {
return {
x: speed*Math.cos(Math.toRad(direction)),
y: speed*Math.sin(Math.toRad(direction))
};
}
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
}
}`