传递变量以便以角度移动子弹

时间:2014-11-10 12:37:50

标签: javascript canvas angle

所以基本上我正在将光标机制射击到我的游戏中。我有一个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 个答案:

答案 0 :(得分:2)

假设您直接希望将vxvy变量从handleMouse方法传递到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};
}

update方法

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

答案 1 :(得分:0)

在handleMouse()中,您不需要将某些坐标返回给事件侦听器,您需要使用坐标调用update()。使用函数参数将信息传递给其他函数。您在函数中定义的变量仅存在于该范围内,并且在您离开该函数后会丢失。

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