If your game is tile-based, checking the distance in tiles can be a simple solution to determine if two players are close enough. For example, you can define that two players are close enough if they are on adjacent tiles:
+--+---+---+---+--+
| | | | | |
+--+---+---+---+--+
| | x | x | x | |
+--+---+---+---+--+
| | x | O | x | | All Xs are adjacent to O
+--+---+---+---+--+
| | x | x | x | |
+--+---+---+---+--+
| | | | | |
+--+---+---+---+--+
Let's assume (x1, y1)
and (x2, y2)
represent the coordinates of player1
and player2
, respectively. By verifying that the absolute difference between x1
and x2
, as well as the difference between y1
and y2
, does not exceed 1 tile (represented by * tileSize
), you can determine if they are overlapping, adjacent, or far apart.
Here's an implementation example:
const KEY_LEFT = 37;
const KEY_RIGHT = 39;
const KEY_UP = 38;
const KEY_DOWN = 40;
let canvas, ctx, closeText;
let playerTurn = 1;
let player1, player2;
let tileSize;
init();
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
closeText = document.getElementById('close');
tileSize = canvas.width / 10;
player1 = new Player(10, 20, 'red');
player2 = new Player(50, 40, 'green');
updateText(areClose(player1, player2));
ctx.strokeStyle = '#888';
window.addEventListener('keyup', onKeyUp, false);
draw();
}
function onKeyUp(e) {
let dx = 0, dy = 0;
// Determine player movement direction
switch (e.keyCode) {
case KEY_LEFT: dx -= tileSize; break;
case KEY_RIGHT: dx += tileSize; break;
case KEY_UP: dy -= tileSize; break;
case KEY_DOWN: dy += tileSize; break;
}
// Update player position
if (playerTurn === 1) {
player1.x += dx;
player1.y += dy;
} else if (playerTurn === -1) {
player2.x += dx;
player2.y += dy;
}
// Switch player turn
playerTurn *= -1;
// Check proximity for combat
const close = areClose(player1, player2);
updateText(close);
// Redraw board and players
draw();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBoard();
drawPlayer(player1);
drawPlayer(player2);
}
function drawBoard() {
// Draw horizontal lines
for (let i = tileSize; i < canvas.width; i += tileSize) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.closePath();
ctx.stroke();
}
// Draw vertical lines
for (let j = tileSize; j < canvas.height; j += tileSize) {
ctx.beginPath();
ctx.moveTo(0, j);
ctx.lineTo(canvas.width, j);
ctx.closePath();
ctx.stroke();
}
}
function drawPlayer(player) {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.size, player.size);
}
function Player(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.size = 10;
}
function areClose(a, b) {
return Math.abs(a.x - b.x) < 2 * tileSize && Math.abs(a.y - b.y) < 2 * tileSize;
}
function updateText(close) {
closeText.innerText = close ? 'Close' : 'Not close';
}
canvas {
border: 1px solid black;
}
<canvas id="canvas" width=100 height=100></canvas>
<p id="close"></p>