JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="canvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
var X = canvas.width / 2;
var Y = canvas.height / 2;
var moveX = 0;
var moveY = 0;
const radius = 24;
var x1, x2;
var y1, y2;
x1 = 400; x2 = 500;
y1 = 200; y2 = 300;
var keys = [];
window.addEventListener("keydown", function (e) {
keys[e.keyCode] = true;
});
window.addEventListener("keyup", function (e) {
keys[e.keyCode] = false;
});
document.onkeydown = checkKey;
var circle_to_line_intersection_x_pos;
var circle_to_line_intersection_y_pos;
function circle_to_line_intersection(x1 , y1 , x2 , y2 , cx , cy , radius)
{
var dx31; // Float
var dx21; // Float
var dy31; // Float
var dy21; // Float
var d; // Float
var dx; // Float
var dy; // Float
var result; // Int Or Bool
// Calculate Closest Point To Circle Center
dx31 = cx - x1;
dx21 = x2 - x1;
dy31 = cy - y1;
dy21 = y2 - y1;
d = ((dx21 * dx21) + (dy21 * dy21));
if(d != 0)
{
d = ((dx31 * dx21) + (dy31 * dy21)) / d;
}
// Clip To The Line Segments Legal Bounds
if (d < 0.0)
{
d = 0;
}
if (d > 1.0)
{
d = 1;
}
dx = cx - (x1 + (dx21 * d)) + moveX;
dy = cy - (y1 + (dy21 * d)) + moveY;
var magnitude = Math.sqrt((dx * dx) + (dy * dy)) // Square Root
if(radius >= magnitude)
{
result = true; // True = Collision Occurred
circle_to_line_intersection_x_pos = -dx;
circle_to_line_intersection_y_pos = -dy;
}
else
{
result = false; // False = No Collision
}
return result;
}
function sliding_collision()
{
// Sliding Collision ( Change Velocity Vector Direction To Point Along The Collision Line : Stops Velocity Vector Pushing Into A Line After A Collision )
var nx = circle_to_line_intersection_x_pos + moveX;
var ny = circle_to_line_intersection_y_pos + moveY;
// Normalise
var magnitude = Math.sqrt( (nx * nx) + (ny * ny) );
if...