为什么我的代理碰撞不起作用 (javascript)
Why my agent collision doesn't work (javascript)
我有一个叫立方体的代理(立方体只是名字,实际上是正方形)。每个立方体都会掉落并停在地面上,我希望他们检测到其他立方体并堆叠起来。
我在使用这种检测碰撞的方法时遇到问题:https://www.youtube.com/watch?v=GY-c2HO2liA&list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA
我做了 2 个 for 循环,但由于某些原因它不起作用。
这是主脚本:
var cubes = [];
var nb = 10; //number of cubes
var gravity = .1;
var sz = 10; //cube size
function setup() {
createCanvas(400, 400);
for (i = 0; i < nb; i++) {
cubes.push(new Cube());
}
}
function draw() {
background(51);
for (var i = 0; i < cubes.length; i++) {
cubes[i].show();
for (var j = 0; j < cubes.length; j++) {
if (i != j && !cubes[i].collide(cubes[j]) && !(cubes[i].pos.y + sz > height)) {
cubes[i].pos.y += gravity;
}
}
}
}
这是在 HTML 文件中与 p5.js 链接的立方体函数:
function Cube() {
this.rx = (round((random(0, width - sz)) / sz) * sz);
this.ry = (round((random(sz, height - sz)) / sz) * sz);
this.pos = createVector(this.rx, this.ry);
this.show = function() {
fill(220);
noStroke();
rect(this.pos.x, this.pos.y, sz, sz);
}
this.collide = function(other) {
if (this.pos.y + sz == other.pos.y && this.pos.x == other.pos.x) {
return true;
} else {
return false;
}
}
}
我希望立方体在落地时堆叠起来,但它们只是相互穿过,完全忽略了我设置的碰撞。
我认为您的问题是因为您使用的是 ==,请尝试修改此行:
if (this.pos.y + sz == other.pos.y && this.pos.x == other.pos.x) {
进入
if (this.pos.y + sz > other.pos.y && this.pos.y <= other.pos.y+sz &&
this.pos.x < other.pos.x+sz && this.pos.x + sz > other.pos.x)
我有一个叫立方体的代理(立方体只是名字,实际上是正方形)。每个立方体都会掉落并停在地面上,我希望他们检测到其他立方体并堆叠起来。
我在使用这种检测碰撞的方法时遇到问题:https://www.youtube.com/watch?v=GY-c2HO2liA&list=PLRqwX-V7Uu6Zy51Q-x9tMWIv9cueOFTFA
我做了 2 个 for 循环,但由于某些原因它不起作用。
这是主脚本:
var cubes = [];
var nb = 10; //number of cubes
var gravity = .1;
var sz = 10; //cube size
function setup() {
createCanvas(400, 400);
for (i = 0; i < nb; i++) {
cubes.push(new Cube());
}
}
function draw() {
background(51);
for (var i = 0; i < cubes.length; i++) {
cubes[i].show();
for (var j = 0; j < cubes.length; j++) {
if (i != j && !cubes[i].collide(cubes[j]) && !(cubes[i].pos.y + sz > height)) {
cubes[i].pos.y += gravity;
}
}
}
}
这是在 HTML 文件中与 p5.js 链接的立方体函数:
function Cube() {
this.rx = (round((random(0, width - sz)) / sz) * sz);
this.ry = (round((random(sz, height - sz)) / sz) * sz);
this.pos = createVector(this.rx, this.ry);
this.show = function() {
fill(220);
noStroke();
rect(this.pos.x, this.pos.y, sz, sz);
}
this.collide = function(other) {
if (this.pos.y + sz == other.pos.y && this.pos.x == other.pos.x) {
return true;
} else {
return false;
}
}
}
我希望立方体在落地时堆叠起来,但它们只是相互穿过,完全忽略了我设置的碰撞。
我认为您的问题是因为您使用的是 ==,请尝试修改此行:
if (this.pos.y + sz == other.pos.y && this.pos.x == other.pos.x) {
进入
if (this.pos.y + sz > other.pos.y && this.pos.y <= other.pos.y+sz &&
this.pos.x < other.pos.x+sz && this.pos.x + sz > other.pos.x)