一旦达到条件就停止

时间:2017-06-09 12:26:48

标签: javascript html canvas

如您所见,我在这里有这段代码:



<!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 = {
    	x: 150,
        y: 296
    };
    var slope = {
    	1: {
        	x: 183,
        	y: 299
        }
    }
    ctx.font = "13px monospace";
    setInterval(function() {
    	player.x += 8;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        }, 50);
    setInterval(function() {
    	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) {
        	monster.x = 1000; monster.y = 1000;
        }
        if (player.x >= slope[1].x - 21) {
        	player.y -= 10;
        }
        }, 50);
    </script>
    
    </body>
    </html>
&#13;
&#13;
&#13;

我想阻止玩家超过10(y - = 10然后停止)一旦触及斜坡而不是继续上升。对此有什么解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以使用在初始和操作后设置为false的状态变量,设置为true:

&#13;
&#13;
<!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 = {
    	x: 150,
        y: 296
    };
    var slope = {
    	1: {
        	x: 183,
        	y: 299
        }
    }
    ctx.font = "13px monospace";
    setInterval(function() {
    	player.x += 8;
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        }, 50);
    var up = false;
    setInterval(function() {
    	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) {
        	monster.x = 1000; monster.y = 1000;
        }
        if (!up && player.x >= slope[1].x - 21) {
        	player.y -= 10;
          up=true
        }
        }, 50);
    </script>
    
    </body>
    </html>
&#13;
&#13;
&#13;

答案 1 :(得分: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)