增加画布的球速

时间:2015-11-16 04:43:36

标签: javascript canvas

希望有人可以提供帮助。我使用帆布制作游戏并试图逐渐提高我的球速(https://developer.mozilla.org/en-US/docs/Games/Workflows/2D_Breakout_game_pure_JavaScript/Game_over)。然而,我的球速从我的球拍上跳了几下之后我的速度达到了狂躁的速度!如何逐步提高速度?

// Declare all the variables for my game
var canvas = document.getElementById('myCanvas')
var ctx = canvas.getContext('2d')
var x = canvas.width / 2    // starting x positon of the ball
var y = canvas.height - 30 // starting y positon of the ball
var dx = 2
var dy = -2
var ballRadius = 10
var paddleHeight = 10
var paddleWidth = 75
var paddleX = (canvas.width - paddleWidth) / 2
var rightPressed = false
var leftPressed = false
var ballSpeed = 10

// make the ball bounce off the walls

// Defining the draw function and clear ball after every draw

// Make canvas draw ball
function drawBall () {
  ctx.beginPath()
  ctx.arc(x, y, ballRadius, 0, Math.PI * 2)
  ctx.fillStyle = '#0095DD'
  ctx.fill()
  ctx.closePath()
}

// Make canvas draw the paddle
function drawPaddle () {
  ctx.beginPath()
  ctx.rect(paddleX, canvas.height - paddleHeight, paddleWidth, paddleHeight)
  ctx.fillStyle = '0095DD'
  ctx.fill()
  ctx.closePath
}

// overall draw function
function draw () {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  drawBall()
  drawPaddle()
  // bounce off the side walls
  if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) { dx = -dx }

  // change y-direction when ball hits paddle, side walls and top wall
  if (y + dy < ballRadius) {
    dy = -dy
  } else if (y + dy > canvas.height - ballRadius) {
    if (x > paddleX && x < paddleX + paddleWidth) {
      clearInterval(timerRef)
      ballSpeed -= 0.01
      setInterval(draw, ballSpeed)
      dy = -dy
    } else {
      alert('Game Over')
      document.location.reload()
    }
  }
  x += dx
  y += dy
  if (rightPressed && paddleX < canvas.width - paddleWidth) {
    paddleX += 7
  } else if (leftPressed && paddleX > 0) {
    paddleX -= 7
  }
}

// To listen for whether user presses keyboard (keydown) or not
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
  }
}

clearInterval(timerRef)
var timerRef = setInterval(draw, ballSpeed)

1 个答案:

答案 0 :(得分:0)

1)您没有在clearInterval中创建的新setInterval上致电draw,因为您实际上从未真正更新timerRef。你最终会在一次碰撞后每帧调用一次draw,然后在两次之后每帧调用两次,等等。

2)你的帧速率似乎取决于球的速度,我不完全理解,你的物理特性与你的帧速率直接相关。

P.S。我将在该教程中跳过并立即切换到requestAnimationFrame。另外,我建议您阅读:http://gameprogrammingpatterns.com/game-loop.html