Facebook
From Abrupt Sheep, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 122
  1.   let backgroundColor = 0;
  2.   let canvasWidth = 600;
  3.   let canvasHeight = 400;
  4.   let paddleWidth = 5;
  5.   let paddleHeight = 60;
  6.   let leftPaddleY = canvasHeight / 2 - paddleHeight / 2;
  7.   let rightPaddleY = canvasHeight / 2 - paddleHeight / 2;
  8.   let ballY = 195;
  9.   let ballX = 295;
  10.   let velocity = 2;
  11.   let velocityY = 0;
  12.   let rightPaddleX = 585;
  13.   let leftPaddleX = 10;
  14.  
  15. function setup() {
  16.   createCanvas(canvasWidth, canvasHeight);
  17. }
  18.  
  19. function draw() {
  20.   background(backgroundColor);
  21.   rect(leftPaddleX, leftPaddleY, paddleWidth, paddleHeight);
  22.   rect(rightPaddleX, rightPaddleY, paddleWidth, paddleHeight);
  23.   ellipse(ballX, ballY, 10);
  24.  
  25. ballX = ballX + velocity;
  26. ballY = ballY + velocityY
  27.  
  28.   if (ballHitPaddle()) {
  29.     velocity = -velocity;
  30.  
  31.   let leftPaddleMiddle = leftPaddleY + paddleHeight / 2;
  32.   let rightPaddleMiddle = rightPaddleY + paddleHeight / 2;
  33.    
  34.     if (ballX < leftPaddleX) {
  35.       velocityY = (leftPaddleMiddle - ballY) /6;
  36.   } else {
  37.     velocityY = (rightPaddleMiddle -ballY) /6;
  38.   }
  39.   }
  40.  
  41.   if (ballY < 0 || ballY > canvasHeight) {
  42.     velocityY = -velocityY;
  43.     }
  44.   if (ballX < 0) {
  45.     console.log ("right wins");
  46.    
  47.     if (ballX > canvasWidth) {
  48.       console.log ("left wins");
  49.     }
  50.      
  51.  if (keyIsDown(UP_ARROW)) {
  52.    rightPaddleY = rightPaddleY - 3;
  53.  }
  54.   if (keyIsDown(DOWN_ARROW)) {
  55.    rightPaddleY = rightPaddleY + 3;
  56.  }
  57.  
  58.    if (keyIsDown(81)) {
  59.    leftPaddleY = leftPaddleY - 3;
  60.  }
  61.   if (keyIsDown(65)) {
  62.    leftPaddleY = leftPaddleY + 3;
  63.  }
  64. }
  65.  
  66.  
  67.  function ballHitPaddle()  {
  68.    // Left Paddle
  69.    if (ballY > leftPaddleY &&
  70.        ballY < leftPaddleY + paddleHeight &&
  71.        ballX < leftPaddleX) {
  72.      return true
  73.    }
  74.      
  75.      // Right Paddle
  76.    if (ballY > rightPaddleY &&
  77.        ballY < rightPaddleY + paddleHeight &&
  78.        ballX > rightPaddleX)  {
  79.      return true
  80.    // No Paddle
  81.    }
  82.    
  83.    return false
  84.