2016年5月24日 星期二

打磚塊遊戲-讓球撞到牆反彈-程式碼3

<html>
<head>
   
    <title>Gamedev Canvas Workshop - lesson 3: bounce off the walls</title>
    <style>* { padding: 0; margin: 0; } canvas { background: #eee; display: block; margin: 0 auto; }</style>
</head>
<body>

<canvas height="320" id="myCanvas" width="480"></canvas>

<script>
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var ballRadius = 10;
    var x = canvas.width/2;
    var y = canvas.height-30;
    var dx = 2; (控制球飛的速度)
    var dy = -2;
    function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI*2);
        ctx.fillStyle = "#0095DD";
        ctx.fill();
        ctx.closePath();
    }
    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawBall();
        if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
            dx = -dx;
        }
        if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
            dy = -dy;
        }
        x += dx;  (避免讓球飛出框外)
        y += dy;
    }
    setInterval(draw, 10);
</script>

</body>
</html>

沒有留言:

張貼留言