Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

72
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 ...

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!