[英]Collision Detection html5 canvas
我在 javascript 中编写了用于碰撞检测的代码,但由于某种原因它不起作用。 当球发生碰撞时,它应该发出警报说“碰撞”,但它是随机发生的警报或根本没有警报。
我在下面附上小提琴的链接: https://jsfiddle.net/vedant12355/b7pvLkwy/1/
还在这里附上所有代码:
<!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>
function a1
做了很多奇怪的事情,我不会尝试弄清楚你在做什么。
最后一次测试
if (p===t){
alert("Collision!")
}
只会在运气好的情况下发生。 如果p = 200.000001
和t = 200
它们相隔百万分之一像素,但它不会显示警报。
当它们之间的距离小于它们的半径之和时,两个圆重叠。 可以在一行中完成if (Math.hypot(x1-x, y1-y) < r + r1) { alert("Collision!") }
或将 function a1
更改为
function a1() {
if (Math.hypot(x1 - x, y1 - y) < r + r1) { alert("Collision!") }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.