pass a variable to move a bullet at angle

856 Views Asked by At

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;    
    }
}
2

There are 2 best solutions below

2
On BEST ANSWER

Maybe this would help, assuming that you directly want to pass vx and vy variables from handleMouse method to update method.

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;    
    }
}
2
On

In handleMouse() you don't need to return some coordinates to the event listener, you need to call update() with the coordinates. Use function parameters to pass info to other functions. Variables you define in functions only exist in that scope and are lost once you leave that function.

function handleMouse(e) {
    ... calculate stuff ...
    update(vx, vy);
    // you can also pass an object as a parameter if you have more complex data:
    // update({vx: vx, vy: vy, name: 'foo', moreStuff: [1, 2, 3]});
}

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