gpt4 book ai didi

javascript - 传递一个变量以一定 Angular 移动子弹

转载 作者:行者123 更新时间:2023-11-29 21:55:09 25 4
gpt4 key购买 nike

所以基本上我目前正在我的游戏中实现射击光标机制。我有一个 mousemove eventListener 来检查鼠标坐标并计算我的 Angular 色应该射击的 Angular 。我只需要将最终的 vx 和 vy 变量从我的 handleMouse 函数传递到我的更新函数,但我不知道如何做。这可能是一个非常简单的解决方案,但由于我对编程还很陌生,所以我无法理解它。非常感谢。

window.addEventListener("mousemove", handleMouse, false);

function getMousePosition(e){
var x, y;
x = e.clientX - backgroundCanvas.getBoundingClientRect().left;
y = e.clientY - backgroundCanvas.getBoundingClientRect().top;
return {x:x, y:y};
}

function handleMouse(e){
var pos = getMousePosition(e);
posx = pos.x; //mouse x position
posy = pos.y; //mouse y position

var delta = {x: posx - player.x, y: posy - player.y}; //y2 - y1, x2 - x1
var angle = Math.atan2(delta.y, delta.x) ;

var vx = Math.cos(angle - (Math.PI/2)) * game.bulletSpeed;
var vy = Math.sin(angle - (Math.PI/2)) * game.bulletSpeed;
return {vx:vx, vy:vy};
}

function update(){
//move bullets - this is where I need to pass the vx and vy variables
var vector = handleMouse(e); // this is probably wrong
vx = vector.vx;
vy = vector.vy;

for (i in game.bullets){
game.bullets[i].x -= vx;
game.bullets[i].y -= vy;
}
}

最佳答案

也许这会有所帮助,假设您直接想将 handleMouse 方法中的 vxvy 变量传递给 update 方法。

function handleMouse(e){    
var pos = getMousePosition(e);
posx = pos.x; //mouse x position
posy = pos.y; //mouse y position

var delta = {x: posx - player.x, y: posy - player.y}; //y2 - y1, x2 - x1
var angle = Math.atan2(delta.y, delta.x) ;

var vx = Math.cos(angle - (Math.PI/2)) * game.bulletSpeed;
var vy = Math.sin(angle - (Math.PI/2)) * game.bulletSpeed;

//call update method
update(vx, vy);

return {vx:vx, vy:vy};
}

更新方法

function update(vx, vy){   
for (i in game.bullets){
game.bullets[i].x -= vx;
game.bullets[i].y -= vy;
}
}

关于javascript - 传递一个变量以一定 Angular 移动子弹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26844023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com