所以我有一个简单的处理草图,块跟随鼠标。它有一个基本的碰撞函数,检测两个矩形之间的交集,然后将矩形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();
}
你好,我更新了您的代码,遵循http://ejohn.org/apps/processing.js/examples/topics/bouncybubbles.html中发现的多对象碰撞示例
这个想法是按以下顺序执行步骤:
我为Block
创建了一个新方法show()
,该方法在冲突检测后更新位置后运行。矩形不会显示在run()
中,因为它们的位置不正确。在安装时调用的方法重叠()
在初始化草图时负责重叠矩形。
希望这有帮助!
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语句添加了一些额外的大括号,即使不必要,也会使代码更加“安全”