gpt4 book ai didi

javascript - 如何设置 setInterval 使其适用于特定的子类

转载 作者:行者123 更新时间:2023-11-30 13:44:41 25 4
gpt4 key购买 nike

我有一个名为 MovingThing 的类,它由一个名为 Monster 的类扩展。每个怪物都需要自己的 setinterval 计时。这是我正在使用的:

游戏板.js

this.monsters = [
new Monster(this, 'monster_0'),
new Monster(this, 'monster_1'),
new Monster(this, 'monster_2')
]

movingThings.js

class Monster extends MovingThing{
constructor(gameboard, dom_id) {
super('monster', 20, document.getElementById(dom_id), gameboard);
}

class MovingThing {

characterType = '';
speed = 0;
dom = null;
gameBoard = null;
step = 4;
direction = 0;
gameLoop = null
size = 40;
x = 0;
y = 0;
sprite = {
left: 0,
right:0,
top: 0,
bottom: 0
};

constructor(characterType, speed, dom, gameboard) {
this.characterType = characterType;
this.speed = speed;
this.dom = dom;
this.gameBoard = gameboard;

self = this;
this.gameLoop = setInterval(function(){self.moveLoop()}, this.speed);
}

moveLoop(){
if (!this.gameBoard.is_active) return;
//if (this.characterType == 'monster') console.log(this.x, this.y)
switch (this.direction) {
case 37:
this.sprite.left -= 2;
break;
case 40:
this.sprite.top += 2;
break;
case 39:
this.sprite.left += 2;
break;
case 38:
this.sprite.top -= 2;
break;
}

this.drawSprite();
if (this.sprite.left % this.size === 0 &&
this.sprite.top % this.size === 0 ){
this.x = this.sprite.left / this.size;
this.y = this.sprite.top / this.size;
this.handleIntersection();
}
// console.log(this.direction)
}

setPosition(grid_x, grid_y){
this.x = grid_x;
this.y = grid_y;
this.sprite.top = grid_y * this.size;
this.sprite.left = grid_x * this.size;
this.drawSprite();
}

drawSprite(){
this.sprite.bottom = this.sprite.top + this.size;
this.sprite.right = this.sprite.left + this.size;

this.dom.style.top = this.gameBoard.gameBoardPosition.top + this.sprite.top + 'px';
this.dom.style.left = this.gameBoard.gameBoardPosition.left + this.sprite.left + 'px';
};

}

发生的只是最后一个怪物的移动,而且它的移动速度是预期速度的 3 倍。就像有 3 个计时器在运行,但它们都移动同一个怪物。

除此代码外,我尝试将 setinterval 放在 Monster 构造函数中,但存在同样的问题。

最佳答案

你的 self 是全局的,所以你不断地覆盖它。使用 let 将其限定在函数范围内:

let self = this;
this.gameLoop = setInterval(function(){self.moveLoop()}, this.speed);

关于javascript - 如何设置 setInterval 使其适用于特定的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59535396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com