javascript - 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?
解决方案
在以下示例中,您必须找到鼠标位置 ( 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>
推荐阅读
- delphi - 使用 THTTPRIO 进行 SOAP 调用时如何强制使用 TLS 1.2?
- android - Android - 在完成第一个活动之前打开另一个活动时未调用 onActivityResult
- python - 如何将 message.text 转换为字符串并将其保存到数据库。如何通过电报机器人下载照片。TelegramBotAPI
- flutter - Flutter:如何调用存储在变量中的类
- autodesk-forge - How to receive the RealityCapture results on an email address
- javascript - 当值 <0 时需要红色的进度条
- svg - 使用 imagemagick 从带有覆盖文本的 SVG 创建 PNG 图标
- flutter - 如何存根不属于类的函数
- flutter - Flutter - 无法在文本字段中编辑文本而不点击它
- css - CSS 右侧的 div 弯曲(提供的示例图片)