gpt4 book ai didi

java - 为什么这些矩形有时会显示它们正在碰撞,即使它们没有碰撞?

转载 作者:行者123 更新时间:2023-11-30 05:25:05 26 4
gpt4 key购买 nike

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

Example of code not working correctly

主要

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);
}
}
}

最佳答案

rect不会围绕中心点绘制矩形,默认情况下,矩形会在左上角位置 (x, y) 绘制,尺寸为 (with高度)。

您有两种解决问题的可能性:

要么改变碰撞检测方法:

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);
}
}
}

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

class Box{

// [...]

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

// [...]
}

关于java - 为什么这些矩形有时会显示它们正在碰撞,即使它们没有碰撞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58847350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com