Search code examples
javascriptmathprocessingtrigonometryp5.js

How do you find x,y coordinate of based on the edge of a circle by looking at my mouse cursor


I'm trying to find x,y coordinate based on trigonometry within the edge of a circle according to my mouse position.

enter image description here

As you can see from the gif image, as your mouse move, the tip of the triangle is always pointing at the edge of the circle as my mouse is moving around the ellipse.

I'm using P5.js and I wish to know how to write this and appreciate if you can walk me through trigonometry behind this, so I can leverage this knowledge and try out more types of visual programming ideas that are in my head.


Solution

  • Compute the vector form the center of the circle (cx, cy) to the mouse position (mouseX, mouseY). Use p5.Vector respectively createVector() to represent the vector and change the magnitude of the vector to the radius of the circle by setMag():

    let v = createVector(mouseX - cx, mouseY - cy).setMag(radius);
    let px = v.x + cx;
    let py = v.y + cy;
    

    respectively

    let cpt = createVector(cx, cy);
    let pt = createVector(mouseX, mouseY).sub(cpt).setMag(radius).add(cpt);
    let px = pt.x;
    let py = pt.y;