I am coding a small game in JavaScript and I am running into a math problem. I am trying to move an object towards the location that I just clicked. I am able to successfully do this with the code below. However I am having difficulty figuring out how to make the velocity constant. If I click close to the object that I am shooting from, the difference in the X/Y is small so dx/dy is slow. If I click far away the dx/dy has high values, so it moves a lot faster.
Here is the code that I have so far.
let relativeXY = relMouseCord(e);
let run = relativeXY[0] - pOne.posX; //<-- This is the distance between the X coords
let rise = relativeXY[1] - pOne.posY; //<-- This is the distance between the Y coords
let angle = Math.atan2(rise,run)*180/Math.PI //<-- Arctan of (change in x and change in Y
tempdx = run * 0.02 //Math.cos(angle)
tempdy = rise * 0.02 //Math.sin(angle)
I attempted to use cos and sin to normalize the speed and was able to make the velocity constant, but the direction of the projectile was incorrect.
Tempdx and tempdy are what is added to the projectile's coordinates to change its position in the next frame.
You're multiplying the angle by
180/Math.PIto convert it from radians to degrees. ButMath.cosandMath.sinboth take input in radians, so you shouldn't do this.