p5.js - 控制对象的自主代理
问题描述
我正在尝试根据 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();
});
}
解决方案
在您的seek()
函数中,使用p5.Vector.sub()
代替this.desired.sub()
and this.steer.sub()
。
推荐阅读
- android - Firebase 查询无法正常工作,未显示所需结果
- github - 如何为 github 配置文件设置默认自定义域
- php - 数据未保存到数据库
- c# - 抛出异常:System.Data.SqlClient.dll 中的“System.Data.SqlClient.SqlException”
- python-3.x - 有什么方法可以将 csv 数据与 Python 中的文本文件连接起来?
- angular - 更新数据时,Angular 组件如何重新渲染?
- python - 如何显示除当前使用 Django 登录的用户之外的所有用户
- python - 在 Python 中使用循环将列表元素添加为字典中的值
- python - pyBAMM 包在 conda forge 频道中不可用,但在他们的网站上
- swift - Swift Combine:如何合并来自多个嵌套发布者的结果?