【问题标题】:Collision Detection html5 canvas碰撞检测html5画布
【发布时间】:2021-04-12 01:27:30
【问题描述】:

我已经在 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>

【问题讨论】:

    标签: javascript html5-canvas collision-detection


    【解决方案1】:

    a1 函数做了很多奇怪的事情,我不会尝试弄清楚你在做什么。

    最后的测试

    if (p===t){
        alert("Collision!")
    }
    

    只有运气好才会发生。如果p = 200.000001 和t = 200 它们相距百万分之一像素,但不会显示警报。

    当它们之间的距离小于它们的半径之和时,两个圆重叠。一行可以搞定if (Math.hypot(x1-x, y1-y) &lt; r + r1) { alert("Collision!") }

    或者把函数a1改成

    function a1() {
        if (Math.hypot(x1 - x, y1 - y) < r + r1) { alert("Collision!") }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多