如何使对象沿鼠标光标的方向旋转?

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

我有一个正方形 ({x,y,width,height}),我想将它旋转某个角度以查看我的光标(p5.js 中的 cursorX, cursorY

如何计算使我的方形点指向光标方向所需的角度?

在以下示例中,您必须找到鼠标位置 (mouseX/mouseY) 到对象 (posX/posY) 的方向。 可以通过减去2个点(posX-mouseYposY-mouseY)来计算鼠标光标位置的向量。矢量的角度可以通过 Math.atan2(y, x):

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

使用rotate()旋转对象。

rotate(angle)

请注意,在这种情况下,对象的顶部朝向鼠标。如果例如对象的右边必须朝向鼠标,然后你必须添加一个偏移角度:

 rotate(angle + radians(-90))

的答案可能也很有趣。

示例:

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>