我有以下错误:
TypeError: Illegal constructor
at new Car (car.js:15:23)
at main.js:7:13汽车构造师在这里排队
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.controls = new Controls();
this.sensor = new Sensor(this);
}在this.sensor = new Sensor(this);上抛出错误
创建汽车对象的方式如下:
const car = new Car(2, 100, 30, 50);
知道我为什么会犯这个错误吗?我想我应该能够使用this作为参数,所以不确定为什么会抛出错误。
这是我使用的类传感器:
class Sensor{
constructor(car){
this.car = car;
this.rayCount = 3;
this.rayLength = 100;
this.raySpread = Math.PI / 4;
this.rays = [];
}
update(){
this.rays = [];
for(let i = 0; i < this.rayCount; i++){
const rayAngle = lerp(
this.raySpread / 2,
- this.raySpread / 2,
i / (this.rayCount - 1)
);
const start = {x : this.car.x, y: this.car.y};
const end = {
x: this.car.x - Math.sin(rayAngle) * this.rayLength,
y: this.car.y - Math.cos(rayAngle) * this.rayLength
};
this.rays.push([start, end]);
}
}
draw(context) {
for(let i = 0; i < this.rayCount; i++){
context.beginPath();
context.lineWidth = 2;
context.strokeStyle = "yellow";
context.moveTo(
this.rays[i][0].x,
this.rays[i][0].y
);
context.lineTo(
this.rays[i][1].x,
this
);
context.stroke();
}
}
}发布于 2022-09-24 05:35:00
从此更改" this“的行。
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.sensor = new Sensor(this);
this.controls = new Controls
to this
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.sensor = new Sensor(this);
this.controls = new Controls
https://stackoverflow.com/questions/72392720
复制相似问题