Ajax调用使精灵运动闪烁javascript

时间:2013-04-14 07:11:34

标签: javascript jquery ajax html5

我刚刚在我的JavaScript / HTML5游戏中为我的主角精灵实现了动作,除了加载现有用户保存的数据之外,一切都很好。

在我的主JavaScript文件中,取决于用户是否点击了新游戏按钮或加载游戏按钮,是加载新游戏还是通过PHP和Ajax从数据库加载用户数据。

如果用户点击新游戏,则会运行以下代码并且播放器移动正常:

 else{
        //set beginning params
        //Change screens
        ui.new_game();

        layer = scene.load("level_"+1);
        layer = $.isArray(layer) ? layer : layer.layers;

        layer.forEach(function(layer){
            if (layer.hasOwnProperty("properties") && layer.properties.hasOwnProperty("collision"))
            {
                scene.collisionLayer(layer);
            }
        });

        gameGUI.set_level(1);
        gameGUI.set_location(20,20);
        gameGUI.init_inv();
        player.init_Player(20,20);
        player.draw();
        last_update = Date.now();

    }

但是如果玩家决定加载他们之前的游戏设置,则运行以下代码,而不是在画布中流动地移动精灵,当按下右键箭头键时,精灵将消失,然后闪烁在某处然后屏幕右侧再次消失。

function game_settings(state){
    if(state == "load"){

        ui.load_game();

        //do ajax call to load user last save
        var dataString = {"user_data": "true"};
        $.ajax({
           type:"POST",
            url:"PHP/class.ajax.php",
            data: dataString,
            dataType: 'JSON',
            async:false,
            success: function(success) {
                player_details_init(success);

            },
            error: function(){
                alert("ERROR in User data");
            }
        });

        layer = scene.load("level_"+level);
        layer = $.isArray(layer) ? layer : layer.layers;

        layer.forEach(function(layer){
            if (layer.hasOwnProperty("properties") && layer.properties.hasOwnProperty("collision"))
            {
                scene.collisionLayer(layer);
            }
        });
        player.init_Player(location_X,location_Y);
        player.draw();
        last_update = Date.now();

    }

我知道Ajax是什么导致了这个问题,因为当我发表评论时,Sprite会像它应该做的那样移动,唯一的问题是我不知道为什么Ajax会导致这种奇怪的行为?

我已将当前版本的游戏上传至HERE,因此如果您愿意,可以见证这种奇怪的行为。

登录使用

  • 访客 - 用户名
  • 来宾 - 密码

感谢您的时间

修改 好的,我已经将问题进一步缩小到变量location_X,location_Y。我坚持使用硬编码的数字,在playr.init中说20,20,这个动作运行正常,但当我使用location_X时,就像你在例子中看到的那样,问题仍然如上所述。

我从Ajax返回成功时调用的函数中检索location_X和location_Y,名为player_details_init。 这是函数:

function player_details_init(success){

    $.each(success, function(key,value){
        if(level == null){
            level = value.level;
        }
        if(location_X == null){
            location_X = value.location_X;
        }
        if(location_Y == null){
            location_Y = value.location_Y;
        }
        //items.push([value.game_item_id, value.quantity]);

        gameGUI.set_level(level);
        gameGUI.set_location(location_X,location_Y);
        gameGUI.init_inv();
    });
}

所以我的猜测是这与这个功能有关,虽然当我做一个console.log时,位置返回正常,精灵确实出现在它应该没有正确移动的地方

1 个答案:

答案 0 :(得分:1)

根据您描述的症状,location_Xlocation_Y似乎是字符串而不是数字。在这种情况下,计算将无法按预期工作(例如,添加将导致连接)。

我建议您在阅读JSON有效负载时尝试将parseInt()应用于这些值(也可能是其他值)。