[英]How to I make a circle constantly follow the mouse pointer forever using event listeners?
我正在嘗試制作Agar.io克隆,一切進行得很好,直到我開始移動鼠標為止。 我將鼠標移動事件添加到文檔中,並且圓圈僅在鼠標移動時才朝鼠標移動,而我希望它在鼠標移動和停止時才移動。 我試圖在鼠標移動時使用它,但它似乎無能為力。 在“處理JavaScript”中,您可以隨時訪問鼠標坐標,但是在JavaScript中,您不能這樣做,而我想知道如何使圓圈不斷跟隨鼠標指針。
這是我的一些鼠標代碼:
document.addEventListener("mousemove", m);
function m(e) {
let mouseX=e.clientX;
let mouseY=e.clientY
mouseX-=player.pos.x;
mouseY-=player.pos.y;
let mouse=Math.atan2(mouseX, mouseY);
player.pos.x+=Math.sin(mouse)/0.3;
player.pos.y+=Math.cos(mouse)/0.3;
if (player.pos.x > 0 && player.pos.x < 900) {
ctx.translate(-Math.sin(mouse)/0.3, 0);
}
if (player.pos.y > 0 && player.pos.y < 900) {
ctx.translate(0, -Math.cos(mouse)/0.3)
}
}
這是我的小提琴: https : //jsfiddle.net/doss2ecd/1/
可能更好的方法是在mousemove上更新全局鼠標坐標。 然后在您的更新/繪制事件中移動播放器並定位相機
您可以嘗試創建一個從畫布中心到鼠標指針的矢量,然后沿着該矢量移動,直到達到游戲領域的邊界。 該位置應使用您的gameloop或setTimeout()更新,例如
function onMouseMove(e) {
var mousePos = convertPosInRelationToCanvasSize(e.clientX,e.clientY)
moveVector = {X:mousePos.x-canvas.HalfWidth,Y:mousePos.y-canvas.HalfHeight}
normalizeVector(moveVector); // adjusts values to -1.0-1.0
}
function moveCircle() {
circle.X += moveVector.X*speed;
circle.Y += moveVector.Y*speed;
}
setTimeout(moveCircle,20); // update circle position every 20ms
畫布尺寸:100x100(中心50:50)
鼠標位置80:20(向上)
moveVector = {X:30,Y:-30} //然后標准化
這樣你的圈子就會向上移動
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.