JSFiddle - React, Tailwind, and code Playground
by Josh Shields
HTML
<h4>Drag circle: turns red if colliding with rect</h4>
<canvas id="canvas" width=300 height=300></canvas>
<p id="debug"></p>
CSS
body{ background-color: ivory; }
#canvas{border:1px solid red;}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "skyblue";
ctx.strokeStyle = "black";
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var isDown = false;
var startX;
var startY;
var circle = {
x: 100,
y: 290,
r: 10
};
var rect = {
x: 100,
y: 100,
w: 40,
h: 100
};
draw();
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = "black";
ctx.stroke();
ctx.strokeRect(rect.x, rect.y, rect.w, rect.h);
}
// return true if the rectangle and circle are colliding
function RectCircleColliding(circle, rect) {
/*
Step#1: Find the vertical & horizontal (distX/distY) distances between the circle’s center and the rectangle’s center
*/
//var distX = Math.abs(circle.x - rect.x - rect.w / 2);
//var distY = Math.abs(circle.y - rect.y - rect.h / 2);
var distX = Math.abs(circle.x - (rect.x + rect.w / 2));
var distY = Math.abs(circle.y - (rect.y + rect.h / 2));
document.getElementById('debug').innerText = 'dists: '+distX + ', ' + distY;
/*
Step#2: If the distance is greater than halfCircle + halfRect,
then they are too far apart to be colliding
*/
//debugger;
if (distX > (rect.w / 2 + circle.r)) {
return false;
}
if (distY > (rect.h / 2 + circle.r)) {
return false;
}
/*
Step#3: If the distance is less than halfRect
then they are definitely colliding
*/
if (distX <= (rect.w / 2)) {
return true;
}
if (distY <= (rect.h / 2)) {
return true;
}
/*
Step#4: Test for collision at rect corner.
Think of a line from the rect center to any rect corner
Now extend that line by the radius of the circle
If the circle’s center is on that line they are colliding at exactly that rect corner
Using Pythagoras formula to...