יצירת לולאת משחק
- כפיר עוזיהו
- 6 בינו׳
- זמן קריאה 2 דקות
עודכן: 7 בינו׳
לולאת המשחק, הינה החלק הכי חשוב בכל משחק אנימציות בזמן אמת לא יעבדו בלי לולאת המשחק וגם המודל/המנוע הפיזיקלי שגם עליו אני אדבר בהמשך בפוסטים אחרים תהיה בעיה גם איתם.
אז יהיו מספר פוסטים על לולאת משחק אני אחלק את הנושא למספר חלקים.
הפרק הראשון יהיה בפוסט זה.
יצירת מחלקת לולאת משחק - הבסיס(חלק 1)

בתוך קטע הקוד ניתן לראות את כל ההערות שכתבתי. מומלץ להשתמש בrequestAnimationFrame בשביל לולאת המשחק לביצועיים מקסימליים. getters וsetters מתודות מאוד חשובות
ליצירת encapsulation חלק חשוב מארכיטקטורת התוכנה.
:GameLoop.js
class GameLoop
{
//Game loop is the most impoprtant part of any game engine or framework it provide the main cycle that keeps the game running
//Game loop constructor
constructor({callback, canvas ,canvasContext, isRunning=true}={})
{
this.callback = callback;
this.canvas = canvas;
this.canvasContext = canvasContext;
this.isRunning = isRunning;
}
//--Getters setters are part of my approch to encapsulation
setCallback(callback)
{
this.callback = callback;
}
getCallback()
{
return this.callback();
}
setCanvasContext(canvasContext)
{
this.canvasContext = canvasContext;
}
getCanvasContext()
{
return this.canvasContext;
}
setCanvas(canvas)
{
this.canvas = canvas;
}
getCanvas()
{
return this.canvas;
}
setIsRunning(isRunning)
{
this.isRunning = isRunning;
}
getIsRunning()
{
return this.isRunning;
}
run()
{
try
{
if(this.getIsRunning())
{
//Use arrow function and requestAnimationFrame for smooth looping and high perfomance---------
const myLoop = ()=>
{
this.getCanvasContext().clearRect(0, 0, this.getCanvas().width, this.getCanvas().height); //Clear canvas before each frame
this.getCallback();
requestAnimationFrame(myLoop);
};
myLoop();
//------------------end of game loop implementation------------------------
//---> keep running the game loop-----------------------
}
else{
//stop the game loop
this.stop();
cancelAnimationFrame(this.run);
}
}
catch(e)
{
console.error("Error in Game Loop: " + e.message);
}
}
stop()
{
//Stopping game loop can be implemented by canceling the requestAnimationFrame
//This is a placeholder for future implementation
this.isRunning = false;
}
}ניתן לראות מספר מתודות - run בכדי להפעיל את הלולאה ו stop בכדי לעצור את פעילות הלולאה. משתנה isRunning הוא הינו משתנה בוליאני והוא קובע אם הלולאה תעבוד או לא.
:frameworkUsage.js
const gameLoop = new GameLoop(callback:()=>{
//Write game logic here
//callback usage pattern
},canvas:canvas, canvasContext:canvasContext, isRunning:true}).run();//run method using chaning - make gameloop work כך משתמשים בלולאת המשחק עם הפרמוורק אשר אני יוצר ומציג בבלוג זה.
בהמשך בניית מנוע המשחק, אני יוסיף עוד אופציות ללולאת המשחק כמו Time Scale(שליטה בזמן) - יצירת סלואו מושן(Slow Motion) קולנועי ועוד דברים מעניינים נוספים שיהיו בתהליך יישום. כרגע בשלב זה עדיין אין אנימציות עד להוספת מערכת Input (קלט) ,מערכת פיזיקה, בינה מלאכותית או אנימציה.


תגובות