2013-04-14 18 views
2

我剛剛在我的JavaScript/HTML5遊戲中實現了我的主要角色精靈的運動,除了當我加載現有用戶保存的數據時,一切都很好。Ajax調用使精靈運動閃爍javascript

在我的主要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(); 

    } 

我知道阿賈克斯什麼,因爲當我註釋掉雪碧移動像它應該做的,唯一的問題是我不知道爲什麼阿賈克斯導致這種怪異的行爲導致的嗎?

我已將當前版本的遊戲上傳到HERE,所以如果您願意,您可以親眼目睹奇怪的行爲。

要登錄使用

  • 客人 - 用戶名
  • 客人 - 密碼

感謝您的時間

編輯 好吧,我已經進一步縮小的問題到變量location_X,location_Y。我堅持在一個硬編碼數字說20,20在playr.init調用移動工作正常,但是當我使用location_X,location_Y就像你在例子中看到的問題仍然如上發生。

我從Ajax返回稱爲player_details_init的成功時調用的函數中檢索location_X和location_Y。 這裏是一個函數:

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位置返回罰款和精靈確實出現在它應該它只是不正確地移動

+0

它看起來像'location_X'和'location_Y'是字符串而不是數字。因此,計算將無法按預期工作(例如,加法會導致串聯)。嘗試在閱讀您的JSON負載時將'parseInt()'應用於這些值。 –

+0

如果你在我身邊我會擁抱你!這根本沒有想到,謝謝你!一直在尋找年齡!,請把它作爲anser,這樣我就可以將它標記爲upvote,謝謝 –

回答

1

從你描述的症狀看,它看起來像location_Xlocation_Y是字符串而不是數字。在這種情況下,計算將無法按預期工作(例如,除了會導致串聯)。

我建議你在閱讀你的JSON有效載荷時嘗試將parseInt()應用於這些值(也可能還有其他值)。