JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas1" width="500" height="500"></canvas>
JavaScript
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
// So lets make two creeps, one at 100,100 and one at 150,150
// And the tower will be at 300,300 with a range of 200
// Lets show some visual aids. Here's the creep's location and the tower's location:
ctx.fillStyle = 'red';
ctx.fillRect(100, 100, 4, 4);
ctx.fillText("creep1", 100, 100);
ctx.fillRect(160, 160, 4, 4);
ctx.fillText("creep2", 160, 160);
ctx.fillRect(300, 300, 4, 4);
ctx.fillText("Tower", 300, 300);
// And lets make the tower's radius visible
ctx.beginPath();
ctx.arc(300, 300, 200, 0, Math.PI * 2, false)
ctx.stroke();
// So we can see visually that it is clearly not in. Lets do the math:
// The math to get the distance between the two is
// Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2))
// Takes two sets of coordinates and returns the distance between them
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2));
}
// Takes two sets of coordinates and returns the squared distance between them. This is faster than checking the distance because it doesnt bother doing a square root
function distanceSquared(x1, y1, x2, y2) {
return Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2);
}
// First lets try with distance. We want to know if the distance is less than 200, but we are only gonna bother outputting the distance because we want to see the exact number for now:
console.log(distance(100,100,300,300)); // distance is 282, so this creep is outside!
console.log(distance(160,160,300,300)); // distance is 197, so this creep is inside!
console.log('the squared distance is: ' + Math.pow(200, 2)); // this lets us know what we are comparing distanceSquared to. The squared distance is 40000.
console.log(distanceSquared(100,100,300,300)); // 80000 - creep is outside!
console.log(distanceSquared(160,160,300,300)); // 39200 - creep is inside!
console.log(distanceSquared(100,300,300,300)); // 40000 - creep is right on...