HTML5 Game - Adding Simple Gravity to object

Introduction

To add gravity to the object, create a new variable named gravity and set it to a constant value of .1:

let gravity =  .1; 

Then we apply this gravity value to the ball object as

ball.velocityy += gravity

Demo

ResultView the demo in separate window

<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);  
function eventWindowLoaded() {//from  w  w  w.  j av  a  2 s . c  o m
  canvasApp();
}

function canvasApp() {
  function  drawScreen () {

    context.fillStyle = '#EEEEEE';
    context.fillRect(0, 0, theCanvas.width, theCanvas.height);
    //Box
    context.strokeStyle = '#000000'; 
    context.strokeRect(1,  1, theCanvas.width-2, theCanvas.height-2);

    
    if (ball.y + ball.radius <= theCanvas.height) {
      ball.velocityy += gravity;
    } else {
      ball.velocityx = 0;
      ball.velocityy = 0;
      ball.y = theCanvas.height - ball.radius;
      
    }
    
    ball.y += ball.velocityy;
    ball.x += ball.velocityx;
    
    context.fillStyle = "#000000";
    context.beginPath();
    context.arc(ball.x,ball.y,ball.radius,0,Math.PI*2,true);
    context.closePath();
    context.fill();

        
  }
  let speed = 4;
  
  let gravity = .1;
  let angle = 305;
  let radians = angle * Math.PI/ 180;
  let radius = 15;
  let vx = Math.cos(radians) * speed;
  let vy = Math.sin(radians) * speed;
  
  
    theCanvas = document.getElementById('canvasOne');
  context = theCanvas.getContext('2d');
  
  let p1 = {x:20,y:theCanvas.height-radius};
  let ball = {x:p1.x, y:p1.y, velocityx: vx, velocityy:vy, radius:radius};
  
  function gameLoop() {
      window.setTimeout(gameLoop, 20);
      drawScreen()  
    }
    
  gameLoop();
  
  
}

</script>

</head>
<body> 
<div style="position: absolute; top: 50px; left: 50px;">

<canvas id="canvasOne" width="500" height="500">
 Your browser does not support the HTML 5 Canvas. 
</canvas>
</div>

</body>
</html>

Related Topic