当能量为0时停止运动

时间:2016-03-08 15:00:24

标签: javascript jquery node.js socket.io

我正在使用node.js,socket.io和create.js创建一个4人游戏。在我的游戏中,每个玩家都有能量,当玩家移动能量正在减少。我想在能量为0或更低时停止玩家。但我无法做到。

服务器端:

socket.on('move', function(data)
                     {
                         var w = data["dir"];
                         var x = data["x"];
                         var y = data["y"];
                         var e = data["energy"];
                         console.log(e);
                                if(w == "down")
                                    y += 5;

                                if(w == "up")
                                    y -= 5;

                                if(w == "left")
                                    x -= 5;

                                if(w == "right")
                                    x += 5;

                                if(e <= 0)
                                {
                                    x+=0;
                                    y+=0;
                                }

                                socket.broadcast.emit("_movement2",data);
                                socket.emit("_movement",{ "X" : x, "Y" : n       y});
 });

客户端:

switch(evt.keyCode)
            {
                case 37:    
                          energy--;
                            $("#energy").css({"width" : energy});
                        socket.emit("move", {"y" : player.playerImage.y,  "x": player.playerImage.x, "dir" : "left", "id":player_id, "energy" : energy});
                            break;
                case 38:    
                            energy--;
                            $("#energy").css({"width" : energy});
                            socket.emit("move", {"y" : player.playerImage.y, "x" : player.playerImage.x, "dir" : "up", "id":player_id, "energy" : energy});


                            break;
                case 39:     
                energy--;
                            $("#energy").css({"width" : energy});
                            socket.emit("move", {"x" : player.playerImage.x, "y" : player.playerImage.y, "dir": "right", "id":player_id , "energy" : energy});

                            break;
                case 40:    
                                energy--;
                            $("#energy").css({"width" : energy});
                socket.emit("move", {"y" : player.playerImage.y, "x" : player.playerImage.x, "dir" : "down", "id":player_id, "energy" : energy});
                break;
            }



        socket.on("_movement", function(data)
        {
            player.playerImage.x = data["X"];
            player.playerImage.y = data["Y"];
                });

感谢您的关注!

1 个答案:

答案 0 :(得分:0)

您的if语句不正确。 你想做的事情是:

if(energy <= 0) {
    //don't move
}
else {
    //move
}