I have written code for collision detection in javascript, but it isnt working for some reason.
when the balls collide, it should give an alert saying "Collision" but it is eather alerting at a random occurence or not at all.
I am attaching a link to the fiddle below:
https://jsfiddle.net/vedant12355/b7pvLkwy/1/
also attaching all the code here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<canvas></canvas><p></p><text></text>
<style>body{
margin:0;
overflow: hidden;
}
p{
position: absolute;
top:0;
z-index: 1;
}
text{
position:absolute;
top:100;
z-index: 1;
left:0;
color:black;
}
</style>
<script>
var ct = document.querySelector('canvas');
ct.width = window.innerWidth;
ct.height = window.innerHeight;
var c = ct.getContext('2d');
var x = 500;
var r = 100;
var d = 10;
var dy = 10;
var y = 100;
var x1 = 100;
var y1 = 500;
var r1 = 100;
var d1 = 10;
var dy1 = 10;
function a(){
requestAnimationFrame(a);
c.clearRect(0, 0, innerWidth, innerHeight);
c.beginPath();
c.arc(x, y, r, 0, Math.PI * 2, false);
c.strokeStyle = 'black';
c.stroke();
c.fillStyle = 'black';
c.fill();
c.closePath();
c.beginPath();
c.arc(x1, y1, r1, 0, Math.PI * 2, false);
c.strokeStyle = 'black';
c.stroke();
c.fillStyle = 'red';
c.fill();
c.closePath();
if(x + r > innerWidth || x-r<0){
d = -d;
}
if(x1 + r1 > innerWidth || x1-r1<0){
d1 = -d1;
}
if(y+r>innerHeight || y-r<0){
dy = -dy;
}
if(y1+r1>innerHeight || y1-r1<0){
dy1 = -dy1;
}
x += d;
y += dy;
x1 += d1;
y1 += dy1;
function a1(){
var b;
var v;
if(x<x1){
b = x1 - x;
}
else if(x>x1){
b = x - x1;
}
else{
b = 0;
}
if(y<y1){
v = y1 - y;
}
else if(y>y1){
v = y - y1;
}
else{
v = 0;
}
var db = Math.sqrt(Math.pow(v, 2) + Math.pow(b, 2));
var p = document.querySelector('p').textContent = db;
var t = document.querySelector('text').textContent = r+r1;
if (p===t){
alert("Collision!")
}
}
a1();
}
a();
</script>
</body>
</html>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…