HTML5 Game - Creating Uniform Circular Motion

Introduction

To create a uniform circular motion, move an object along the radius of a defined circle.

If we know the radius, we can use cosine and sine to find the x and y locations of the moving object.

The equations to find the locations of an object moving uniformly on a circle are as follows:

x = radius * cosine(angle) 
y = radius * sine(angle) 

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 a v a2 s . co  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);
      
      ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
      ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;
      
      circle.angle += ball.speed;
   
      context.fillStyle = "#000000";
      context.beginPath();
      context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
      context.closePath();
      context.fill();
   
   }
   
   let radius = 100;
   let circle = {centerX:250, centerY:250, radius:125, angle:0}
   let ball = {x:0, y:0,speed:.1};
      
    theCanvas = document.getElementById('canvasOne');
   context = theCanvas.getContext('2d');
   
   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