a new one
a new one

Reputation: 89

How to make an object rotate in the direction of my mouse cursor?

I have a square ({x,y,width,height}) and I'd like to rotate it by some angle to look at my cursor (which is cursorX, cursorY in p5.js)

how can I calculate the angle needed to make my square point in the direction of my cursor?

Upvotes: 3

Views: 5366

Answers (1)

Rabbid76
Rabbid76

Reputation: 210918

You've to find the direction of the mouse position (mouseX/mouseY) to the object (posX/posY) in the following example). The vector of the position to the mouse cursor can be calculated by subtracting the 2 points (posX-mouseY, posY-mouseY). The angle of an vector can be calculated by Math.atan2(y, x):

let angle = Math.atan2(mouseY-posY, mouseX-posX);

Use rotate() to rotate the object.

rotate(angle)

Note in this case the top of the object is orientated to the mouse. If e.g. the right of the object has to be orientated to the mouse, then you've to add an offset angle:

 rotate(angle + radians(-90))

The answer to Limit the length of a line may also be of interest.

Example:

function setup() {
    createCanvas(600, 200);
}

function draw() {
    background(0);
    
    let posX = width/2;
    let posY = height/2;
    
    let angle = Math.atan2(mouseY-posY, mouseX-posX);

    translate(posX, posY);
    rotate(angle)
    //rotate(angle + radians(-90))

    stroke(255, 255, 0)
    fill(255, 0, 0)
    beginShape();
    vertex(-3, -3);
    vertex(50, -3);
    vertex(50, -6);
    vertex(60, 0);
    vertex(50, 6);
    vertex(50, 3);
    vertex(-3, 3);
    vertex(-3, -3);
    endShape()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

Upvotes: 3

Related Questions