我正在尝试学习编码列车的 Daniel Shiffman 介绍的“自主转向行为”课程。 See Video Tutorials Here
这些课程是使用 P5.js 库提供的,但我想使用纯 JavaScript 继续学习。
我已经创建了自己的 vector
类,以及一个表示受力控制的对象的 vehicle
类。
当我单独运行 vector
类方法时,add
和 subtract
方法按预期工作。但是,当我尝试在 this.velocity.add(desiredVelocity)
类中执行 vehicle
时,velocity
向量返回 'NaN'
独立运行的代码(按预期工作)是
let v1 = new Vector(10,10)
let v2 = new Vector(20,30)
console.log(v1.add(v2)) // Outputs Vector(30,40)
我忽略或不知道导致 this.velocity.add(desiredVelocity)
返回 NaN
的原因是什么?
class Vector{
constructor(x,y){
this.x = x == undefined ? 0 : x,this.y = y == undefined ? 0 : y
}
magnitude(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}
setMagnitude(newMagnitude){
this.x = this.x * newMagnitude / this.magnitude();
this.y = this.y * newMagnitude / this.magnitude();
return new Vector(this.x,this.y);
}
add(vector){
this.x += vector.x;
this.y += vector.y;
return new Vector(this.x,this.y)
}
static subtract(vector1,vector2){
return new Vector(vector1.x - vector2.x,vector1.y - vector2.y);
}
}
class Vehicle {
constructor(){
this.position = new Vector();
this.velocity = new Vector();
this.maxSpeed = 10;
}
seek(target) {
let desiredVelocity = Vector.subtract(target.position,this.position);
desiredVelocity.setMagnitude(this.maxSpeed);
this.velocity.add(desiredVelocity)
console.log('new velocity',this.velocity) // Returns NaN
}
}
class Target{
constructor(){
this.position = new Vector();
}
}
const vehicle = new Vehicle();
const target = new Target()
vehicle.seek(target)