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.
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;
}
}
Maybe this would help, assuming that you directly want to pass
vx
andvy
variables fromhandleMouse
method toupdate
method.and the
update
method