如何清除前一个球的位置?

时间:2016-06-30 15:05:16

标签: javascript html canvas html5-canvas pong

我第一次尝试画布并获得我期望的动作,但它并没有清除球的先前位置。我在每次抽球之前使用beginPath()。所以,我不明白为什么它不起作用。有什么建议?任何和所有的帮助非常感谢!谢谢!

window.onload = function(){

  var field = document.getElementById('field');
  var ctx = field.getContext('2d');

  var height = field.height;
  var width = field.width;

  //ball radius 
  var radius = 10


  //game speed 
  var gameSpeed = 2;

  //ball position 
  var ballx = 150; 
  var bally = 20;

  //ball speed
  var xBallSpeed = radius * 2;
  var yBallSpeed = radius * 2;

  //ball direction
  var xBallDir   = 1;
  var yBallDir   = 1;

  //player 
  var playerx = 50; 
  var playery = 180;
  var playerWidth = 40;
  var playerHeight = 20;

   //goal 
  var goalx = 50; 
  var goaly = 210;
  var goalWidth = 200;
  var goalHeight = 40;


  function draw() {

    //draw ball
    ctx.beginPath();
    ctx.fillStyle = "#000";
    ctx.arc(ballx, bally, radius, 0, Math.PI*2,false);
    ctx.fill();
    ctx.closePath();



    //draw goal
    ctx.beginPath();
    ctx.strokeStyle = "#000";
    ctx.rect(goalx, goaly, goalWidth, goalHeight); //y = field.height - goal.height
    ctx.closePath();
    ctx.stroke();


    //draw player
    ctx.beginPath();
    ctx.fillStyle = "#666";
    ctx.rect(playerx, playery, playerWidth, playerHeight); //y = field.height - goal.height
    ctx.closePath();
    ctx.fill();

    //change position of ball
    ballx = ballx + xBallSpeed + xBallDir;
    bally = bally + yBallSpeed + yBallDir;


    //does it hit the paddle? 
    //does it hit the goal?
    //does it hit the right, left or bottom wall?
  //   if(ballx >= width + radius) {
  //     xBallDir = -1;  
  //   }

  //   if(ballx <= width + radius){
  //     xBallDir  = 1; 
  //   }  
  // }

  setInterval(draw, gameSpeed); 
}

0 个答案:

没有答案
相关问题