2015-12-18 71 views
2

如何在擊球時讓球移動得更快!如何在擊球時讓球移動得更快?

 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 = 'ABCDEF'.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> 

回答

2

修改抽獎功能的反彈代碼:

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以修改比例因子。