2017-06-09 179 views
0

正如你所看到的,我有這個代碼在這裏:停止一旦條件達成

<!DOCTYPE html> 
 
    <html> 
 
    <body> 
 
    
 
    <canvas id="myCanvas" width="500" height="300" 
 
    style="border:1px solid #d3d3d3;"> 
 
    Your browser does not support the canvas element. 
 
    </canvas> 
 
    
 
    <script> 
 
    var canvas = document.getElementById("myCanvas"); 
 
    var ctx = canvas.getContext("2d"); 
 
    var player = { 
 
     x: 0, 
 
     y: 297.3 
 
    }; 
 
    var monster = { 
 
    \t x: 150, 
 
     y: 296 
 
    }; 
 
    var slope = { 
 
    \t 1: { 
 
     \t x: 183, 
 
     \t y: 299 
 
     } 
 
    } 
 
    ctx.font = "13px monospace"; 
 
    setInterval(function() { 
 
    \t player.x += 8; 
 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
     }, 50); 
 
    setInterval(function() { 
 
    \t ctx.fillText("\\o/",player.x, player.y) 
 
     ctx.fillText(">:)",monster.x, monster.y) 
 
     ctx.fillText("/",slope[1].x, slope[1].y) 
 
     ctx.fillText("_______________________",0,296); 
 
     ctx.fillText("_______________________",189,286); 
 
     if (player.x >= monster.x - 25) { 
 
     \t monster.x = 1000; monster.y = 1000; 
 
     } 
 
     if (player.x >= slope[1].x - 21) { 
 
     \t player.y -= 10; 
 
     } 
 
     }, 50); 
 
    </script> 
 
    
 
    </body> 
 
    </html>

我想停止從上升超過10(Y播放器 - = 10則停止)一旦觸及斜坡而不是繼續向上。有沒有解決方案?

回答

1

可以使用的狀態變量,設置初始和行動後假的,設置爲true:

<!DOCTYPE html> 
 
    <html> 
 
    <body> 
 
    
 
    <canvas id="myCanvas" width="500" height="300" 
 
    style="border:1px solid #d3d3d3;"> 
 
    Your browser does not support the canvas element. 
 
    </canvas> 
 
    
 
    <script> 
 
    var canvas = document.getElementById("myCanvas"); 
 
    var ctx = canvas.getContext("2d"); 
 
    var player = { 
 
     x: 0, 
 
     y: 297.3 
 
    }; 
 
    var monster = { 
 
    \t x: 150, 
 
     y: 296 
 
    }; 
 
    var slope = { 
 
    \t 1: { 
 
     \t x: 183, 
 
     \t y: 299 
 
     } 
 
    } 
 
    ctx.font = "13px monospace"; 
 
    setInterval(function() { 
 
    \t player.x += 8; 
 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
 
     }, 50); 
 
    var up = false; 
 
    setInterval(function() { 
 
    \t ctx.fillText("\\o/",player.x, player.y) 
 
     ctx.fillText(">:)",monster.x, monster.y) 
 
     ctx.fillText("/",slope[1].x, slope[1].y) 
 
     ctx.fillText("_______________________",0,296); 
 
     ctx.fillText("_______________________",189,286); 
 
     if (player.x >= monster.x - 25) { 
 
     \t monster.x = 1000; monster.y = 1000; 
 
     } 
 
     if (!up && player.x >= slope[1].x - 21) { 
 
     \t player.y -= 10; 
 
      up=true 
 
     } 
 
     }, 50); 
 
    </script> 
 
    
 
    </body> 
 
    </html>

0

當然,你的時間間隔存儲在一個變量,然後清除它,當你需要到:

var myInterval = setInterval(function() { 
     player.x += 8; 
     ctx.clearRect(0, 0, canvas.width, canvas.height); 
}, 50); 

// Whenever you want to stop it 
clearInterval(myInterval) 
相關問題