【问题标题】:Why do these rectangles sometimes show that they are colliding even though they are not?为什么这些矩形有时显示它们正在碰撞,即使它们没有碰撞?
【发布时间】:2019-11-13 23:49:53
【问题描述】:

当我运行代码时,它会生成 16 个具有随机大小、随机位置和随机颜色的矩形。如果它与另一个矩形碰撞,它应该变成白色。大多数情况下它工作得很好,但是当矩形不与任何东西碰撞时,它们经常会变成白色。

主要

int boxCount = 16;
Box[] boxes = new Box[boxCount];

void setup(){
  size(500, 500);

  for(int i = 0; i < boxCount; i++){
    boxes[i] = new Box(random(50, width - 50), random(50, height - 50), random(20, 50), random(20, 50), color(random(0, 255), random(0, 255), random(0, 255)));
  }
}

void draw(){
  for(int i = 0; i < boxCount; i++){
    boxes[i].create();
    for(int x = 0; x < boxCount; x++){
      if(boxes[i] != boxes[x]){
        boxes[i].collide(boxes[x]);
      }
    }
  }
}

class Box{
  float x;
  float y;
  float w;
  float h;
  color c;

  Box(float _x, float _y, float _w, float _h, color _c){
    x = _x;
    y = _y;
    w = _w;
    h = _h;
    c = _c;
  }

  void create(){
    fill(c);
    rect(x, y, w, h);
  }

  void collide(Box o){
    float right = x + (w / 2);
    float left = x - (w / 2);
    float top = y - (h / 2);
    float bottom = y + (h / 2);

    float oRight = o.x + (o.w / 2);
    float oLeft = o.x - (o.w / 2);
    float oTop = o.y - (o.h / 2);
    float oBottom = o.y + (o.h / 2);

    if(right > oLeft && left < oRight && bottom > oTop && top < oBottom){
      c = color(255, 255, 255);
    }
  }
}

【问题讨论】:

    标签: java processing collision-detection rectangles


    【解决方案1】:

    rect 不会围绕中心点绘制矩形,默认情况下矩形绘制在左上角位置(xy),大小为(withheight)。

    你有 2 种可能性来解决这个问题:

    要么改变碰撞检测方法:

    class Box{
    
        // [...]
    
        void collide(Box o){    
            if(x < o.x+o.w  && o.x < x+w && y < o.y+o.h && o.y < y+h){
                c = color(255, 255, 255);
            }
        }
    }
    

    或者设置CENTERrectMode(),这将导致矩形按照您的预期绘制:

    class Box{
    
        // [...]
    
        void create(){
            fill(c);
            rectMode(CENTER);
            rect(x, y, w, h);
        }
    
        // [...]
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多