自治代理操纵一个对象

Autonomous Agents steering an object

我正在尝试根据 Nature of Code 的第一个自治代理示例应用转向力,但我遗漏了一些东西。我确实得到了 desired/steer 个要更新的向量,但是对象只是移动到右下方并且 checkEdges() 停止工作。我在目标变量中放置了各种 x,y 值,但似乎没有任何效果。我试过在 sketch.js 中调用 seek(),但后来我想也许可以将它放在 update() 中。我做错了什么?

我的目标是让它移动到不断变化的 mouseX、mouseY 目标,就像在 Dan 的示例中一样,但我硬编码了 x、y 值只是为了调试。

这是我的人class:

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();
  });
}

实时代码:https://editor.p5js.org/OMTI/sketches/sgGe8CaZH

在您的 seek() 函数中,使用 p5.Vector.sub() 代替 this.desired.sub()this.steer.sub()