Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

73
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda