我想嘗試創建一個在主循環之外擁有自己的獨立循環的演員的概念證明 - 我創建了類似的東西,但是我希望知道是否有一些明顯的問題,或者我是否完全錯誤。基本上我想知道是否正確的方式來處理「內部」循環將使用此,或者如果有更好的方式(在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