Search code examples
javascriptmathconstantsvelocityangle

Moving ball at constant rate with angle


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 rise = relativeXY[1] - pOne.posY; //<-- This is the distance between the Y coords
let run = relativeXY[0] - pOne.posX; //<-- This is the distance between the X coords

let angle = Math.atan2(rise,run)*180/Math.PI 
console.log('tan angle ' + Math.tan(angle))
console.log('acutal angle '+ angle)

bullet.x = pOne.posX
bullet.y = pOne.posY

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.


Solution

  • normalize your direction vector (run,rise) to unit size:

    tempdx = run  * 0.02 / sqrt((run*run)+(rise*rise))
    tempdy = rise * 0.02 / sqrt((run*run)+(rise*rise))
    

    or use goniometrics (but do not convert to [deg] as goniometrics expect [rad] !!!)

    let angle = Math.atan2(rise,run)
    console.log('tan angle ' + Math.tan(angle))
    console.log('acutal angle '+ angle*180/Math.PI)
    tempdx = cos(angle) * 0.02
    tempdy = sin(angle) * 0.02
    

    ... assuming 0.02 is your wanted speed ...