所以我有这个简单的处理草图,其中块跟随鼠标。它具有基本的碰撞功能,它检测两个矩形之间的交叉点,然后设置矩形A的位置等于矩形B的位置减去矩形A的宽度(假设矩形B在A的前面)。不幸的是,这种方法是不够的,并且矩形略微相互重叠。我真的希望矩形完美地排列,好像它们是一条矩形条。有没有办法做到这一点?这是我下面的可运行草图:
class Block {
color c = color(random(255), random(255), random(255));
float x = random(width);
float speed = random(3, 6);
void run() {
float dir = mouseX - x;
dir /= abs(dir);
x += dir * speed;
fill(c);
rect(x, 300, 30, 60);
}
void collide() {
for (Block other : blocks) {
if (other != this) {
if (x + 30 > other.x && x + 30 <= other.x + 15)
x = other.x - 30;
else if (x < other.x + 30 && x > other.x + 15)
x = other.x + 30;
}
}
}
}
Block[] blocks = new Block[6];
void setup() {
size(600, 600);
for (int i = 0; i < blocks.length; i++)
blocks[i] = new Block();
}
void draw() {
background(255);
for (Block b : blocks) {
b.run();
b.collide();
}
}
void mousePressed() {
setup();
}
答案 0 :(得分:1)
您好我按照http://ejohn.org/apps/processing.js/examples/topics/bouncybubbles.html
中的多对象碰撞示例更新了您的代码我们的想法是按此顺序执行步骤:
我为display()
创建了一个新方法Block
,该方法在碰撞检测后更新位置后运行。矩形不会显示在run()
中,因为它们的位置不正确。
在初始化草图时,设置时调用的方法overlap()
会处理重叠的矩形。
希望这有帮助!
class Block {
color c = color(random(255), random(255), random(255));
float x = random(width);
float speed = random(3, 6);
void run() {
float dir = mouseX - x;
dir /= abs(dir);
x += dir * speed;
}
void display() {
fill(c);
rect(x, 300, 30, 60);
}
void collide() {
for (Block other : blocks) {
if (other != this) {
if (x + 30 > other.x && x + 30 <= other.x + 15) {
x = other.x - 30;
}
else if (x < other.x + 30 && x > other.x + 15) {
x = other.x + 30;
}
}
}
}
void overlap() {
for (Block other : blocks) {
if (other != this) {
if (x + 30 > other.x && x + 30 <= other.x + 30) {
x = other.x - 30;
}
}
}
}
}
Block[] blocks = new Block[6];
void setup() {
size(600, 600);
for (int i = 0; i < blocks.length; i++) {
blocks[i] = new Block();
}
for (Block b : blocks) {
b.overlap();
}
}
void draw() {
background(255);
for (Block b : blocks) {
b.run();
b.collide();
b.display();
}
}
void mousePressed() {
setup();
}
PS还为1行添加了一些额外的大括号if if尽管不必要使代码更多&#34;安全&#34;