我试图根据代码的第一个自治代理的性质来应用方向力,但我遗漏了一些东西。我确实需要更新所需的/方向向量,但随后对象简单地移动到右下角,checkEdges()停止工作。我已经在target变量中放入了各种x,y值,但似乎都不能正常工作。我尝试过在sketch.js中调用seek(),但是我想也许应该把它放在update()中。我做错了什么?
我的目标是让它移动到一个不断变化的mouseX,mouseY目标,就像丹的例子一样,但我已经硬编码了x,y值,只是为了调试。
下面是我的Person类:
class Person {
constructor(){
this.location = createVector(random(width),random(height));
this.velocity = createVector(random(-1,1), random(-1,1));
this.acceleration = createVector(-0.01,0.001);
this.maxspeed = 2;
this.maxforce = 0.01;
this.desired = createVector();
this.steer = createVector();
this.target = createVector(200,200);
}
update() {
this.velocity.add(this.acceleration);
this.velocity.limit(this.maxspeed);
this.location.add(this.velocity);
this.acceleration.mult(0);
this.seek();
}
display() {
fill(0);
stroke(255);
strokeWeight(2);
ellipse(this.location.x, this.location.y, 10, 10);
text(this.target,this.location.x, this.location.y);
}
applyForce(force) {
this.acceleration.add(force);
}
seek() {
this.desired = this.desired.sub(this.target,this.location);
this.desired.normalize();
this.desired.mult(this.maxspeed);
this.steer = this.steer.sub(this.desired,this.velocity);
this.applyForce(this.steer);
this.steer.limit(this.maxforce);
}
checkEdges() {
if ((this.location.x > width) || (this.location.x < 0)) {
this.velocity.x = this.velocity.x * -1;
}
if ((this.location.y > width) || (this.location.y < 0)) {
this.velocity.y = this.velocity.y * -1;
}
}
}下面是sketch.js:
let people = [];
function setup() {
createCanvas(400, 400);
let p1 = new Person();
people.push(p1);
}
function draw() {
background(0);
people.forEach((p) => {
p.update();
p.checkEdges();
p.display();
});
}发布于 2020-10-26 14:46:31
在seek()函数中,使用p5.Vector.sub()而不是this.desired.sub()和this.steer.sub()。
https://stackoverflow.com/questions/64528021
复制相似问题