首页 > 解决方案 > 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?

标签: javascriptprocessingp5.js

解决方案


在以下示例中,您必须找到鼠标位置 ( mouseX/ mouseY) 到对象 ( posX/ ) 的方向。posY鼠标光标位置的矢量可以通过减去 2 个点 ( posX-mouseY, posY-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>


推荐阅读