HTML5 Game - Moving Between Two Points: The Distance of a Line

Introduction

The following code shows how to move an object from point A to point B at a constant rate of speed.

In mathematics, to find the length of a line is to use the Pythagorean theorem:

A2 + B2 = C2

In this equation, C is the unknown side of a triangle when A and B are already known.

Suppose that we will move our circle from 20,250 to 480,250:

let p1 = {x:20,y:250}; 
let p2 = {x:480,y:250}; 

The first step is to calculate the differences between the second and first x and y points:

let dx = p2.x - p1.x; 
let dy = p2.y - p1.y; 

To determine the distance value:

let distance = Math.sqrt(dx*dx + dy*dy); 

Next, to calculate how many moves it will take the object to move at the given value of speed.

let moves = distance/speed; 

Then we find the distance to move both x and y on each move.

let xunits = (p2.x - p1.x)/moves; 
let yunits = (p2.y - p1.y)/moves; 

Demo

ResultView the demo in separate window

<!DOCTYPE html>  
<html> 
<head> 
<style> 
#canvas { /*from w  w w . j a va  2s  . c o  m*/
  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);
    if (moves > 0 ) {
      moves--;
      ball.x += xunits;
      ball.y += yunits;
    }
    points.push({x:ball.x,y:ball.y});
    
    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:250};
  let p2 = {x:480,y:250};
  let dx = p2.x - p1.x;
  let dy = p2.y - p1.y;
  let distance = Math.sqrt(dx*dx + dy*dy);
  let moves = distance/speed;
  let xunits = (p2.x - p1.x)/moves;
  let yunits = (p2.y - p1.y)/moves;
  let ball = {x:p1.x, y:p1.y};
  let points = new Array();
  
  theCanvas = document.getElementById('canvas');
  context = theCanvas.getContext('2d');
  
  function gameLoop() {
      window.setTimeout(gameLoop, 20);
      drawScreen()  
    }
    
  gameLoop();
</script> 
</body> 
</html>

Related Topic