gpt4 book ai didi

java - 矩形碰撞 - 不需要的重叠。 (处理IDE)

转载 作者:太空宇宙 更新时间:2023-11-04 06:09:30 25 4
gpt4 key购买 nike

所以我有这个简单的处理草图,其中 block 跟随鼠标移动。它有一个基本的碰撞函数,检测两个矩形之间的交集,然后将矩形 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 中找到的多对象碰撞示例更新了您的代码

想法是按以下顺序执行步骤:

  1. 根据每个物体的速度和方向更新其位置
  2. 检查碰撞并根据新约束调整位置
  3. 显示对象

我为 Block 创建了一个新方法 display(),该方法在碰撞检测后更新位置后运行。这些矩形不会在 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 语句添加了一些额外的大括号,尽管不必要,但使代码更加“安全”

关于java - 矩形碰撞 - 不需要的重叠。 (处理IDE),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909437/

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