HTML5 Game - Moving on a Vector

Introduction

Moving between two points is easy.

Sometimes we don't have a point to move to, we only have a point to start from.

For this kind of situation we need a vector as a means to move your object.

A vector is a quantity in physics.

It has both magnitude and direction.

The magnitude is the speed value of the moving object.

And the direction is an angle value that the object will move upon.

The following code sets the speed value (magnitude) as the number of pixels the object will move on every step.

We will set the speed to 5 pixels.

We will also set the starting point (p1) for the object to 20,20:

let speed = 5; 
let p1 = {x:20,y:20}; 

Then we set the angle value (direction) of movement to 45 degrees.

In mathematics, a flat line represents the 0 angle.

A vector with an angle of 45 degrees would be down and to the right on the canvas.

During calculation we need to convert it to radians.

Use the standard formula to convert degree to radian: radians = angle * Math.PI/ 180.

let angle = 45; 
let radians = angle * Math.PI/ 180; 

To calculate the number of pixels to move our object on each step, we use

  • the radians (direction) and
  • speed (magnitude),
  • the Math.cos() (cosine) and
  • Math.sin() (sine):
let xunits = Math.cos(radians) * speed; 
let yunits = Math.sin(radians) * speed; 

To get the point we add xunits and yunits to ball.x and ball.y:

ball.x += xunits; 
ball.y += yunits; 

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { //from  ww w  .  ja va 2 s . com
  border:1px solid #03F; 
  background:#CFC; 
} 
</style> 
</head> 
<body> 
<canvas id="canvas" width="640" height="480"></canvas> 
<script> 

  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 += xunits; 
      ball.y += yunits; 


      context.fillStyle = "#000000"; 
      context.beginPath(); 
      context.arc(ball.x,ball.y,15,0,Math.PI*2,true); 
      context.closePath(); 
      context.fill(); 

   }   let speed = 5; 
   let p1 = {x:20,y:20}; 
   let angle = 45; 
   let radians = angle * Math.PI/ 180; 
   let xunits = Math.cos(radians) * speed; 
   let yunits = Math.sin(radians) * speed; 
   let ball = {x:p1.x, y:p1.y}; 

   theCanvas = document.getElementById("canvas"); 
   context = theCanvas.getContext("2d"); 

   function gameLoop() { 
     window.setTimeout(gameLoop, 20); 
     drawScreen() 
   } 
   gameLoop(); 

</script> 



</body> 


</html>

Related Topic