如何让球在击球时移动得更快?
Posted
技术标签:
【中文标题】如何让球在击球时移动得更快?【英文标题】:How to make the ball move faster when it hits paddle? 【发布时间】:2016-03-24 17:30:51 【问题描述】:如何让球在击球时移动得更快!
var canvas = document.getElementById("myCanvas");var ctx = canvas.getContext("2d"); var dx = 2;var dy = -2; var w = canvas.width, h = canvas.height; 变量 x = w/2;变量 y = h-30; var 球半径 = 10; 变种颜色 = 获取颜色(); 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" ></canvas>
【问题讨论】:
【参考方案1】:修改draw函数中的弹跳代码:
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
来修改比例因子。
【讨论】:
以上是关于如何让球在击球时移动得更快?的主要内容,如果未能解决你的问题,请参考以下文章