Processing 如何检查x和y上两个方形对象之间的碰撞?(p5.js)

Processing 如何检查x和y上两个方形对象之间的碰撞?(p5.js),processing,collision-detection,p5.js,Processing,Collision Detection,P5.js,如何测试两个方形对象之间的碰撞? 我有一个玩家和一个方块物体,我想检查它们是否相互碰撞 我尝试过使用很多碰撞检测算法,但它们在我的项目中似乎不起作用,或者我没有正确地编写它们 这是我的播放器碰撞函数,开始时它定义了x、y位置和固定变量 this.testCollisions = function(other){ if (this.x+20 < other.x || this.x > other.x+other.w || this.y+20 < other

如何测试两个方形对象之间的碰撞? 我有一个玩家和一个方块物体,我想检查它们是否相互碰撞

我尝试过使用很多碰撞检测算法,但它们在我的项目中似乎不起作用,或者我没有正确地编写它们

这是我的播放器碰撞函数,开始时它定义了x、y位置和固定变量

this.testCollisions = function(other){
    if (this.x+20 < other.x || this.x > other.x+other.w ||
        this.y+20 < other.y || this.y > other.y+other.h) {
      print("collision")
      this.grounded = true;
    } else {
      this.grounded = false;
    }
  }
它在一开始也开始下降,即使我在一开始就把它设置在了街区上。 谢谢你抽出时间

函数播放器(){
x=宽度/2+10;
该点y=高度/2-20;
这是真的;
this.show=函数(){
填充(255);
正方形(这个x,这个y,20);
}
this.testCollisions=函数(其他){
如果(this.x+20other.x+other.w||
this.y+20other.y+other.h){
打印(“冲突”)
这是真的;
}否则{
this.grounded=false;
}
}
this.affectGravity=函数(){
如果(!this.grounded)
这个。y+=1;
}
}
功能块(x、y、植草){
this.grassed=grassed;//bool
this.x=x;//浮点
这个。y=y;
这个h=40;
这是w=40;
这1.gh=15;
这1.gw=40;
this.render=函数(){
如果(这是草){
填充(“AF7250”);
rect(this.x,this.y,this.w,this.h);
填充(“869336”);
rect(this.x,this.y,this.gw,this.gh);
}
}
}
var块;
var播放器;
var接地=真;
函数设置(){
createCanvas(400400);
块=新块(高度/2,宽度/2,真);
player=新玩家();
}
函数绘图(){
背景(120);
block.render();
player.show();
if(键向下(左箭头)){
player.x--;
}否则如果(键向下(右箭头)){
player.x++;
}
冲程重量(1);
player.testCollisions(block);
player.affectGravity();
控制台日志(播放器接地);
}
功能键按下(){
如果(player.grounded&&keyCode==32){
for(设i=0;i<10;i++)
player.y-=1;
}
}

要检查与矩形的碰撞,必须检查矩形在两个维度上是否重叠

对于每个尺寸,都有以下可能的情况(例如尺寸x):

不重叠:

x1-x1+w1
+----+
+----+
x2+w2
x1-x1+w1
+----+
+----+
x2+w2
重叠

x1-x1+w1
+--------------+
+----+
x2+w2
x1-x1+w1
+----+
+---------------+
x2+w2
x1-x1+w1
+---------+
+----------+
x2+w2
x1-x1+w1
+----------+
+----------+
x2+w2
这意味着,如果

x1
这会导致以下情况:

this.testCollisions=函数(其他){
如果(this.x
函数播放器(){
x=宽度/2+10;
这个y=10;
这是真的;
this.show=函数(){
填充(255);
正方形(这个x,这个y,20);
}
this.testCollisions=函数(其他){
如果(this.x

要检查与矩形的碰撞,必须检查矩形在两个维度上是否重叠

对于每个尺寸,都有以下可能的情况(例如尺寸x):

不重叠:

x1-x1+w1
+----+
+----+
x2+w2
x1-x1+w1
+----+
+----+
x2+w2
重叠

x1-x1+w1
+--------------+
+----+
x2+w2
x1-x1+w1
+----+
+---------------+
x2+w2
x1-x1+w1
+---------+
+----------+
x2+w2
x1-x1+w1
+----------+
+----------+
x2+w2
这意味着,如果

x1
这个
this.x = x; // float
this.y = y;
this.h = 40;
this.w = 40;