传递变量以便以角度移动子弹
so basically I am currently implementing shooting at cursor mechanic into my game. I have a mousemove eventListener to check for mouse coordinates and to calculate the angle at what my character should shoot. I just need to pass the final vx and vy variables from my handleMouse function to my update function, but I can't figure out how. It's probably going to be very simple solution, but I can't get my head around it since I am pretty new to programming. Thank you very much.
所以基本上我目前正在将光标机制射击到我的游戏中。我有一个mousemove eventListener来检查鼠标坐标并计算我的角色应该拍摄的角度。我只需要将最终的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;
}
}
2 个解决方案
#1
2
Maybe this would help, assuming that you directly want to pass vx
and vy
variables from handleMouse
method to update
method.
也许这会有所帮助,假设您直接想要将handleMouse方法中的vx和vy变量传递给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};
}
and the update
method
和更新方法
function update(vx, vy){
for (i in game.bullets){
game.bullets[i].x -= vx;
game.bullets[i].y -= vy;
}
}
更多相关文章
- 1. 总是从ID选择器开始继承 在jquery中最快的选择器是ID选择
- 创建一个对外界只读的属性,但是我的方法仍然可以设置
- js学习之路2: JavaScript 变量
- js中的indexOf以及startsWith和endsWith方法
- 让Heroku的配置变量在node.js中工作
- 深究js(三)——变量
- AngularJs:在内部调用$ http或$ resource时,让方法同步返回
- 使用append方法将对象转换为字符串
- javascript变量:全局?还是局部?这个得注意