圆/圆碰撞在圆碰撞之前发生

问题描述 投票:0回答:1

我设置了一个简单的 p5.js 程序,在屏幕上绘制两个圆圈,其中一个圆圈的沉积由光标确定,当它们接触时,不动的圆圈会改变颜色。代码如下:

let r1 = 70;
let r2 = 90;

let x2;
let y2;

function setup() {
  createCanvas(400, 400);
  x2 = width/2;
  y2 = height/2;
}

function draw() {
  background(220);
  
  circle(mouseX, mouseY, r1);
  let distance = sqrt((x2 - mouseX)*(x2 - mouseX) + (y2 - mouseY)*(y2 - mouseY));
  push();
  if (distance <= r1 + r2) {
    fill(56, 45, 78);
  }
  circle(x2, y2, r2);
  pop();
}

我进行碰撞检测的方法是将两个圆之间的距离与其半径之和进行比较。如果前者劣于或等于后者,则通常应记录为碰撞并更改静止圆圈的颜色。然而,事实并非如此:

如您所见,碰撞检测在发生任何接触之前就启动了,我不知道为什么。

javascript collision-detection collision p5.js
1个回答
2
投票

circle
函数的第三个参数是直径,而不是半径。将半径乘以 2。

使用

dist
函数计算 2 点之间的距离。

let r1 = 70;
let r2 = 90;

let x2;
let y2;

function setup() {
    createCanvas(400, 400);
    x2 = width/2;
    y2 = height/2;
}

function draw() {
    let distance = dist(mouseX, mouseY, x2, y2);

    background(220);
    circle(mouseX, mouseY, r1*2);
    push();
    if (distance <= r1 + r2) {
        fill(56, 45, 78);
    }
    circle(x2, y2, r2*2);
    pop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.