【问题标题】:Rectangle collision detection in Arrays in Processing处理中的数组中的矩形碰撞检测
【发布时间】:2013-12-17 20:44:36
【问题描述】:

所以我是一个非常新的程序员,我正在尝试弄清楚如何在数组中获取矩形以检测碰撞。我试着思考了一下,找到了一些我认为可行的例子,但到目前为止还没有。

这是我的代码,不是很多。

我有时会在框靠近屏幕顶部时收到消息,但不知道为什么。

Box [] b = new Box[1];

float x,y,w,h;

void setup(){
  size(800,800);
  x=random(width);
  y=random(height);
  w=random(200);
  h=random(200);


  b[0] =  new Box(x,y,w,h);

}

void draw(){
  background(0);
  x=random(width);
  y=random(height);
  w=25;
  h=25;

  for(int j = 0; j<b.length;j++){
    for(int k = 0; k<b.length;k++){
      if(j!=k){
        b[j].contact(b[k]);

      }


    }

  }

  for(int i=0;i<b.length;i++){
    b[i].run();


  }



}


void keyPressed(){

  if(key =='n'){

    Box boxnew = new Box(x,y,w,h);
    b = (Box[]) append(b,boxnew);



  }


}


class Box{

  float x,y,w,h,c1,c2,c3,ii,xmo,ymo;

 Box(float mx,float my,float mw,float mh){

   x=mx;
   y=my;
   w=mw;
   h=mh;
   c1=150;
   c2=50;
   c3=200;
   xmo=1;
   ymo=1;


 } 
  void run(){
    maker();
    mover();
    wcolli();


  }

  void maker(){
    ii=random(-1,1);
    c1+=ii;
    c2+=ii;
    c3+=ii;
    fill(c1,c2,c3);
    rect(x,y,w,h);

  }

  void mover(){
    x+=xmo;
    y+=ymo;


  }

  void wcolli(){

    if(x>800-w||x<1){
        xmo*=-1;
      }
      if(y>800-h||y<1){
        ymo*=-1;
      }


  }
  void contact(Box b){

    if((b.x>=this.x&&b.x<=this.w||b.w>=this.x&&b.w<=this.x) && (b.h>=this.y||b.y<=this.h)){
      println("hit");



    }
    if((b.y<=this.h&&b.y>=this.y||b.h<=this.h&&b.h>=this.y) && (b.x<=this.w||b.w>=this.x)){
      println("hit");


    }


  }
}

【问题讨论】:

标签: arrays processing collision


【解决方案1】:

您的碰撞检测存在一些问题。最重要的是您尝试使用宽度和高度(wh),就好像它们是绝对位置一样。它们实际上是相对于每个框的左上角的,所以这就是为什么事情似乎不起作用的原因。在进行任何比较之前,您必须计算实际的右下角位置。

您还必须非常小心您的if 条件。当您将 AND 与 OR(&amp;&amp;||)等结合使用时,最好使用括号来阐明逻辑运算的优先级。

对于像这样简单的轴对齐矩形碰撞,这里有一个我觉得有用的方法:

void contact(Box b) {

    // Calculate the bottom-right corners of the boxes.
    float myX2 = x + w;
    float myY2 = y + h;
    float otherX2 = b.x + b.w;
    float otherY2 = b.y + b.h;

    // If this box is entirely to the left of box b, then there is no collision.  
    if (x < b.x && myX2 < b.x) return;

    // If this box is entirely to the right of box b, then there is no collision.
    if (x > otherX2 && myX2 > otherX2) return;

    // If this box is entirely above box b, then there is no collision.
    if (y < b.y && myY2 < b.y) return;

    // If this box is entirely below box b, then there is no collision.
    if (y > otherY2 && myY2 > otherY2) return;

    // If we reach this point, the boxes haven't missed each other.
    // Therefore, there must be a collision.
    println("hit");

}

这是通过检查一个盒子可能错过另一个盒子的每一种可能情况来确定碰撞。如果它确定它们没有错过彼此,那么逻辑上肯定有碰撞。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多