碰到桨时如何使球移动得更快!

  var canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d");
    var dx = 2;var dy = -2;
    var w = canvas.width, h = canvas.height;
    var x = w/2;var y = h-30;
    var ballRadius = 10;
    var color = getColor();
    var paddleHeight = 10;var paddleWidth = 75;var paddleX = (w-paddleWidth)/2;
    var rightPressed = false;
    var leftPressed = false;

    document.addEventListener("keydown", keyDownHandler,false);
    document.addEventListener("keyup", keyUpHandler,false);
function keyDownHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = true;
    }
    else if(e.keyCode == 37) {
        leftPressed = true;
    }
}

function keyUpHandler(e) {
    if(e.keyCode == 39) {
        rightPressed = false;
    }
    else if(e.keyCode == 37) {
        leftPressed = false;
    }
}

function getColor() {
        var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function drawBall() {
    ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = color;
    ctx.fill();
    ctx.closePath();
}

function drawPaddle() {
    ctx.beginPath();
    ctx.rect(paddleX, h-paddleHeight, paddleWidth, paddleHeight);
    ctx.fillStyle = "#eee";
    ctx.fill();
    ctx.closePath();
}

function draw() {
        ctx.clearRect(0,0,w,h);
    drawBall();
        drawPaddle();
        if(x + dx < ballRadius || x + dx > w-ballRadius) {
        dx = -dx;
            color = getColor();
        }

        if(y + dy < ballRadius) {
        dy = -dy;
            color = getColor();
        }else if(y + dy > h-ballRadius) {
        if(x > paddleX && x < paddleX + paddleWidth) {
            dy = -dy;
        }
        else {
            alert("GAME OVER");
        }
    }

    if(rightPressed && paddleX < w-paddleWidth) {
    paddleX += 7;
    }
    else if(leftPressed && paddleX > 0) {
            paddleX -= 7;
    }
    x += dx;
    y += dy;
}

    setInterval(draw, 10);
/*left arrow: 37
up arrow: 38
right arrow: 39
down arrow: 40*/

* {
    background-color: #224;
    padding: 0; margin: 0;
}
canvas {
    background: #555;
    display: block;
    margin: 10px auto;
}

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

最佳答案

在绘图函数中修改退回代码:

if(y + dy < ballRadius) {
    dy = -dy;
    color = getColor();
}
else if(y + dy > h-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy * 1.1;
    }

注意最后一行:
dy = -dy * 1.1;

这意味着每次击球时dy都会增加10%。您可以更改1.1来修改比例因子。

09-25 20:05