我想尝试创建一个在主循环之外拥有自己的独立循环的演员的概念证明 - 我创建了类似的东西,但是我希望知道是否有一些明显的问题,或者我是否完全错误。基本上我想知道是否正确的方式来处理“内部”循环将使用此,或者如果有更好的方式(在live()函数内): setTimeout(( )=> {this.live()},100);为javascript中的每个实例化类创建自己的循环
其次的问题是要知道破坏的实例化类,withing类的,喜欢的东西的最佳方式“this.destroy()” - 现在我只删除从容器对象的连接
例这里:https://codepen.io/tommica/pen/qmNXYL
我将粘贴代码本身也:
<ul id="simple-log"></ul>
<script>
// We will store out actors as "id" => "actor"
let actors = {};
// Custom logging functionality for a simple ul list
const sLog = (text) => {
let li = document.createElement('li');
li.innerHTML = text;
document.getElementById('simple-log').appendChild(li);
};
const randomNum = (min,max) => { return Math.floor(Math.random() * max) + min; }
// Actor definition
class Actor {
constructor(name, id) {
this.id = id;
this.name = name;
this.gender = randomNum(1,2) === 1 ? 'male' : 'female'; // Random gender
this.lastTime = null;
}
live() {
// Get the current time, and log every 5 seconds
let now = Date.now();
let difference = now - this.lastTime;
if(difference > 5000) {
sLog(`Actor "${this.name}" Log - Difference: ${difference}`);
this.lastTime = now;
}
// Determine if the actor died of a tragic accident
if(randomNum(1,100000) < 5) {
// Something tragic happened, that caused this actor to die
this.die();
} else {
// I'm pretty sure that this is not the best way, but for some reason just
// setTimeout(this.live, 1); does not work
setTimeout(() => {this.live()}, 100);
}
}
die() {
// Log the death
sLog(`Actor "${this.name}" died`);
// This seems really a wrong way to do this, should not need to rely on an element outside of the scope - something else should do this, but how?
delete actors[this.id];
}
}
// Function to spawn a new actor
let spawnActor =() => {
let id = 'a'+randomNum(1,9000000);
sLog('Spawning an actor');
let actorInstance = new Actor(id, id); // Rejoice!
actorInstance.live();
actors[id] = actorInstance;
}
// Simple loop that simulates the rendering of the screen
let lastTimeAnimated = null;
let mainAnimationLoop =() => {
// Logs every 5 seconds to the log
let now = Date.now();
let difference = now - lastTimeAnimated;
if(difference > 5000) {
sLog(`Main Animation Loop Log - Difference: ${difference}`);
lastTimeAnimated = now;
}
window.requestAnimationFrame(mainAnimationLoop);
}
// Simple loop that simulates a normal game main loop
let lastTime = null;
let mainLoop =() => {
// Mainloop logs every 5 seconds to the log
let now = Date.now();
let difference = now - lastTime;
if(difference > 5000) {
sLog(`Main Loop Log - Difference: ${difference}`);
lastTime = now;
}
// Random actor spawner
if(randomNum(1,10000) < 5) {
spawnActor(); // It truly is a blessed day!
}
setTimeout(mainLoop, 1);
}
// Should be obvious
let init =() => {
mainAnimationLoop();
mainLoop();
}
// Let's get started!
init();
</script>
目前还不清楚你在问什么。请询问关于特定代码的具体问题。 “我想知道我是否做错了”不是一个具体问题。描述一个具体的目标,解释你在实现这个目标方面有什么问题,以及你用目前的代码观察到什么,然后准确描述你想要的帮助。 – jfriend00