![](/img/trans.png)
[英]How to rotate the object the same regardless of the direction of the camera?
[英]How to make an object rotate in the direction of my mouse cursor?
我有一個正方形( {x,y,width,height}
),我想將它旋轉某個角度以查看我的光標(即cursorX, cursorY
、cursorY)
如何計算使正方形指向光標方向所需的角度?
在以下示例中,您必須找到鼠標位置 ( 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))
Limit the length of a line的答案可能也很有趣。
例子:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.