嘿,我想用 canvas 和 js 制作这个检测圆圈之间碰撞的小程序

Hey, i want to make this little program with canvas and js which detects collisions between circles

我正在学习 canvas 并使用 JS 在其上渲染内容,并且我正在尝试制作一个简单的碰撞检测程序,使碰撞中涉及的角变成某种颜色。到目前为止..它有点管用,这只是意味着它不起作用:D我有时只看到随机的圆圈变成绿色,而不是那些真正碰撞的圆圈。

所以我想 post 在这里让大家看看,看看能找到什么。提前致谢!

我认为问题出在 'collisions' 函数中,但我不太明白它是什么。

顺便说一句,我也愿意接受有关改进此代码的建议。

这是 html 和 css

<html lang="es">
    <head>
        <link rel="stylesheet" href="index.css">
        <meta charset="utf-8">
        <title>bubbles</title>
    </head>
    <body>

        <p id="fpsIndicator"></p>

        <canvas id="cnv"></canvas>    


    </body>


    <footer>
        <script src="Circle.js"></script>
        <script src="index.js"></script>
    </footer>

</html>
#cnv{
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    /*background-color: blue;*/
}

这是主要的 JS 文件和 Circle class

let fpsInd = document.getElementById("fpsIndicator");
let canvas = document.getElementById("cnv");
let ctx = canvas.getContext("2d");

let frames = 0;
let fps = 0;
let lastCallTime;

let bubbles = 35;
let arrBubbles = [];

const RADIAE = 50;
const COLLISION_COLOR = "green";

adjustCanvas();
window.addEventListener("resize", adjustCanvas);





for(let i = 0; i < bubbles; i++){

    let x = randomInteger(RADIAE, canvas.width-RADIAE);
    let y = randomInteger(RADIAE, canvas.height-RADIAE);

    if(i == 0){
        arrBubbles.push(new Circle(x, y, RADIAE, "blue"));
        continue;
    }

    for(let j = 0; j < arrBubbles.length; j++){

        let d = distance(x, y, arrBubbles[j].x, arrBubbles[j].y);

        if(d <= RADIAE*2){
            x = randomInteger(RADIAE, canvas.width-RADIAE);
            y = randomInteger(RADIAE, canvas.height-RADIAE);
            j = -1;
        }        
    }

    arrBubbles.push(new Circle(x, y, RADIAE, "blue"));
}




loop();
function loop(){
    frames++;
    getFPS();

    if(frames % 3 == 0) 
        fpsInd.innerHTML = "FPS: "+fps;


    ctx.clearRect(0,0,window.innerWidth, window.innerHeight);


    arrBubbles.forEach( (item)=> {
       item.draw(ctx); 
       item.move(canvas.width, canvas.height);    
    });

    collisions();

    requestAnimationFrame(loop);
}


function collisions(){

    for(let i = 0; i < arrBubbles.length; i++){

        let first = arrBubbles[i];

        for(let p = 0; p < arrBubbles.length; p++){

            let second = arrBubbles[p];

            let d = distance(first.x, first.y, second.x, second.y);

            if(d <= first.radius + second.radius){
                second.color = COLLISION_COLOR;
                first.color = COLLISION_COLOR;
            }
            else {
                second.color = "blue";
                first.color = "blue";
            }
        }
    }

}



function distance(x1, y1, x2, y2){
    let distX = x2-x1;
    let distY = y2-y1;

    return Math.sqrt(distX*distX + distY*distY);
}



function randomInteger(min, max){
    return Math.floor(Math.random() * (max-min+1) + min);
}


function adjustCanvas(){
     canvas.setAttribute("width", window.innerWidth);
     canvas.setAttribute("height", window.innerHeight);
}


function getFPS(){

    let delta;

    if(!lastCallTime){
        lastCallTime = Date.now();
        fps = 0;
        return;
    }

    delta = (Date.now() - lastCallTime) / 1000;
    lastCallTime = Date.now();
    fps = Math.floor(1/delta);
}
class Circle{

    constructor(x, y, radius, color){
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;

        this.velocity = {
            X: randomInteger(1, 3),
            Y: randomInteger(1, 3)
        }
    }


    move(canvasW, canvasH){


        if(this.x+1 >= canvasW-this.radius || this.x-1 <= this.radius)
            this.velocity.X = -this.velocity.X;

        if(this.y+1 >= canvasH-this.radius || this.y-1 <= this.radius)
            this.velocity.Y = -this.velocity.Y;


        this.x += this.velocity.X;
        this.y += this.velocity.Y;
    }

    draw(ctx){

        ctx.strokeStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
        ctx.stroke();

    }
}

到目前为止做得很好。您已正确设置 game/animation 的所有基础知识。你是对的——唯一真正的问题是 collisions 函数。看看里面发生了什么。

它选择了一个圆,称之为first。然后对于屏幕上的每个其他圆圈

  • 如果它们相交,它会将两种颜色都更改为碰撞颜色
  • 如果它们不相交,它会将两种颜色改回默认值

现在再看一遍,并考虑如果当 first 圆检查碰撞时实际首先与它碰撞的圆会发生什么。然后在该循​​环中发生的最后一件事将是检查它与其他圆圈(不与之碰撞)的碰撞并将它们的所有颜色更改回默认值。

基本上,您需要重新考虑如何创建这两个循环的逻辑。例如,我建议添加一个布尔标志(例如,colliding),在内循环完成后可以对其进行检查——甚至可能将其添加为 Circle 实例的 属性。因此,如果 first 与内循环中的某物发生碰撞,则设置 first.colliding = true。在你的 Circle draw() 函数中,你可以根据这个 属性.

设置颜色

幸运的是,这些循环的设置方式实际上覆盖了另一个错误。您没有考虑 second 圆圈何时与 first 圆圈是同一个对象(它与自身的距离始终为零,因此应该始终变为绿色......但上面的错误总是变为回来了)。您可以通过在内部循环中添加这样的检查来解决这个问题:

if(first !== second)if(i !== p)

非常感谢!! facepalm 我怎么会错过那个嘿嘿,我去把 .colliding 属性 添加到圆圈中。我已经改变了绘图和碰撞功能,但仍然没有用,现在所有的圆圈都永久地用碰撞颜色绘制。这是新代码:

function collisions(){


    let p, quitLooping;
    let first, second, d;

    for(let i = 0; i < arrBubbles.length; i++){

        first = arrBubbles[i];
        p = 0;
        quitLooping = false;

        while(p < arrBubbles.length && !quitLooping){

            second = arrBubbles[p];
            d = distance(first.x, first.y, second.x, second.y);            

            if( i !== p)     
                if(d <= first.radius + second.radius){
                    first.colliding = true;
                    quitLooping = true;
                }
                else 
                    first.colliding = false;

            p++;
        }
    }

}

draw(ctx){

        (this.colliding) ? ctx.strokeStyle = COLLISION_COLOR : ctx.strokeStyle = this.color;

        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
        ctx.stroke();

    }