首页 > 解决方案 > 控制对象的自主代理

问题描述

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

我的目标是让它移动到不断变化的 mouseX,mouseY 目标,就像在 Dan 的示例中一样,但我硬编码 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();
  });
}

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

标签: p5.js

解决方案


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


推荐阅读