Search code examples
javascriptmathp5.js

Calculate point B coordinates knowing angle and distance from point A


Can someone help me with a math thing. I'm trying to calculate the travel distance from point A to point b. this is what i have so far: https://editor.p5js.org/Marcel0024/sketches/Np03rgmxO I can't get the **angle ** to work, in this case i want the circle to be drawn the direction of the mouse click.

Calculate angle formula i got here: https://maththebeautiful.com/angle-between-points/

New point formula i got here: Angle between two Vectors 2D

But i can't get them to work together.

So i have (using mouse position as Point B)

function mouseClicked(){
  var angle = Math.atan2(mouseY - point1.y, mouseX - point1.x)

  const x = point1.x + Math.sin(angle) * travelDistance;
  const y = point1.y - Math.cos(angle) * travelDistance;
  
  circle(x, y, 10)
}

But the angle is way off


Solution

  • You don't really need an angle, a vector would be enough

    const canvas = document.querySelector('canvas')
    const ctx = canvas.getContext('2d')
    
    const A = {
      x: canvas.width / 2,
      y: canvas.height / 2
    }
    
    const balls = 10
    
    canvas.addEventListener('mousemove', (e) => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      const vector = getVector(A, getMousePos(canvas, e))
      
      for (let i = 1; i <= balls; i += 1) {
        const x = A.x + vector.x * 20 * i
        const y = A.y + vector.y * 20 * i
        ctx.fillStyle = `hsl(${i * 360 / balls}, 50%, 50%)`
        ctx.beginPath()
        ctx.arc(x, y, 5, 0, Math.PI * 2)
        ctx.closePath()
        ctx.fill()
      }
    })
    
    function getVector(A, B) {
      const vector = {
        x: B.x - A.x,
        y: B.y - A.y
      }
      const magnitude = Math.sqrt(vector.x ** 2 + vector.y ** 2)
      const normalized = {
        x: vector.x / magnitude,
        y: vector.y / magnitude
      }
      return normalized
    }
    
    function getMousePos(canvas, evt) {
      const rect = canvas.getBoundingClientRect()
      return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
      }
    }
    canvas {
      border: 1px solid black;
    }
    <canvas></canvas>