Side collisions using JavaScript

I have the following JavaScript code. Using the WASD keys, I want to control its movement. What I want to do now is that the black square if it collides with the red square would stop. It shouldn’t pass through the red square but I have little to no idea how to detect side collisions.

This is what I have tried so far. It is able to stop when the black square hits one of the edges. Now I want it to do the same but also with the red square on the other side for all sides of the red square.

var canvas;
var context;
var ctx;
var rectX = 10;
var rectY = 10;

var object = {
  height: 50,
  width: 50,
  x: 10,
  y: 10,
  //color: "#FF0000"        
}

var spd = 100;
window.onload = function() {
  canvas = document.getElementById("canvas1");
  context = canvas.getContext("2d");
  ctx = canvas.getContext("2d");
  canvas.width = 400;
  canvas.height = 400;
  fillRect();
}

function fillRect() {
  context.beginPath();
  context.fillStyle = "#ffffff";
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.beginPath();
  context.fillStyle = "black";
  context.fillRect(rectX, rectY, 30, 30);
  //obstacle
  ctx.beginPath();
  ctx.fillStyle = "red";
  ctx.fillRect(230, 100, object.width, object.height);
}

function onkeydown(e) {
  if (e.keyCode == 68 && rectX + 30 < canvas.width) {
    rectX++;
  } else if (e.keyCode == 65 && rectX > 0) {
    rectX--;
  } else if (e.keyCode == 87 && rectY > 0) {
    rectY--;
  } else if (e.keyCode == 83 && rectY + 30 < canvas.height) {
    rectY++;
  }
  fillRect();
}

window.addEventListener("keydown", onkeydown);
<canvas id="canvas1" style="border: 1px solid black"></canvas>

14 thoughts on “Side collisions using JavaScript”

Leave a Comment