2017-05-18 84 views
0

所以我正在研究一個基本的射擊遊戲,其中一部分涉及在屏幕上移動目標。我使用babylon.js作爲引擎,我的目標是讓目標在屏幕上顯示0.75秒,然後消失0.5秒,然後重新出現在不同的隨機位置。當前代碼我具有該是這樣的:Javascript在屏幕上移動目標?

function moveTarget(canvas, scene){ 
    setTimeout(function(){ 
    scene.meshes[10].visibility = 0; //how I access the target object 
    randX = genRandNum(minX, maxX); //This is a separate function that works 
    randY = genRandNum(minY, maxY); 
    scene.meshes[10].position = new BABYLON.Vector3(randX, randY, 
       scene.meshes[10].position.z); 
    scene.meshes[10].visibility = 1; 
    x ++; 
    if (x < amount){ 
     moveTarget(canvas, scene); 
    } 
    }, tarDuration * 1000) 

    } 

其成功地以外的所有目標的出現之間的0.5秒的延時,即目前它從位置閃爍到位置與之間沒有空格。我在想我需要第二次setTimeout,但我不完全確定如何包含它或它會去哪裏。任何推動正確的方向將不勝感激。

回答

0

我會這樣做的方式是設置一個完整週期時間(0.75 s + 0.5 s)的超時時間,然後在0.5 s延遲時間內設置另一個超時時間。

function moveTarget(canvas, scene){ 
    setTimeout(function(){ 
     setTimeout(function(){ 
      // Your other code 
      x ++; 
      if (x < amount){ 
       moveTarget(canvas, scene); 
      } 
     }, yourDelayHere) 
    }, tarDuration * 1000) 
} 

其中yourDelayHere給出所需的0.5秒延遲。我創建了Babylon.js playround,其中顯示了一個簡化示例here