Graphics & Rendering
Outline:
Canvas Context:
- The
CanvasRenderingContext2D
object provides the methods for drawing on the canvas. - It’s accessed using
canvas.getContext('2d')
. - The
draw()
method in theGame
class uses this context to clear the canvas and draw sprites, animations, and other game elements. - Refer to the
Game
class insrc/game.ts
: src/game.ts
- The
Sprite Sheets:
- Sprite sheets are images containing multiple sprites used for animations.
Game
class stores sprite sheet images using theImage
object.src/images/sprites.png
: src/images/sprites.png
Animations:
Game
class contains agetSprite
method that retrieves the correct sprite from the sprite sheet based on the animation frame, direction, and sprite type.- The
update()
method in theGame
class callsgetSprite
to update the animation frame and position. - The
draw()
method uses this information to draw the correct sprite on the canvas at the desired location.
Drawing Methods:
CanvasRenderingContext2D
offers various methods for drawing on the canvas.drawImage
is used to draw sprites from the sprite sheet.fillRect
is used to draw filled rectangles for objects like walls.strokeRect
is used to draw outlines for objects like the game board.beginPath
,moveTo
,lineTo
,arc
, andclosePath
are used to draw custom shapes for objects like pellets.
Colors and Styles:
- The
fillStyle
andstrokeStyle
properties of theCanvasRenderingContext2D
object are used to set the fill color and stroke color. - These properties are used in the
draw()
method to style the game elements.
- The
Text Rendering:
- The
fillText
method is used to draw text on the canvas. - The
font
property of theCanvasRenderingContext2D
object is used to set the font style, size, and weight. - The
textAlign
property is used to align the text horizontally. - Refer to
src/game.ts
: src/game.ts
- The
Game Loop:
- The
Game
class contains aloop
method that handles updating the game state and redrawing the canvas at a set frame rate. - The
requestAnimationFrame
method is used to control the animation loop.
- The
Pac-Man Movement:
- Pac-Man’s movement is controlled by the
updatePacManPosition
method in theGame
class. - The
dx
anddy
variables represent Pac-Man’s velocity in the horizontal and vertical directions. - The
update()
method updates Pac-Man’s position based on these values. - Refer to
src/game.ts
: src/game.ts
- Pac-Man’s movement is controlled by the
Ghost Movement:
- Ghosts’ movement is handled by the
updateGhostPosition
method in theGame
class. - Each ghost has its own
dx
anddy
values, determining their direction. - The
update()
method updates each ghost’s position based on theirdx
anddy
. - The ghosts follow predefined paths and use a scatter mode for a short period.
- Refer to
src/game.ts
: src/game.ts
- Ghosts’ movement is handled by the