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 the Game class uses this context to clear the canvas and draw sprites, animations, and other game elements.
    • Refer to the Game class in src/game.ts: src/game.ts
  • Sprite Sheets:

    • Sprite sheets are images containing multiple sprites used for animations.
    • Game class stores sprite sheet images using the Image object.
    • src/images/sprites.png: src/images/sprites.png
  • Animations:

    • Game class contains a getSprite method that retrieves the correct sprite from the sprite sheet based on the animation frame, direction, and sprite type.
    • The update() method in the Game class calls getSprite 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, and closePath are used to draw custom shapes for objects like pellets.
  • Colors and Styles:

    • The fillStyle and strokeStyle properties of the CanvasRenderingContext2D object are used to set the fill color and stroke color.
    • These properties are used in the draw() method to style the game elements.
  • Text Rendering:

    • The fillText method is used to draw text on the canvas.
    • The font property of the CanvasRenderingContext2D 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
  • Game Loop:

    • The Game class contains a loop 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.
  • Pac-Man Movement:

    • Pac-Man’s movement is controlled by the updatePacManPosition method in the Game class.
    • The dx and dy 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
  • Ghost Movement:

    • Ghosts’ movement is handled by the updateGhostPosition method in the Game class.
    • Each ghost has its own dx and dy values, determining their direction.
    • The update() method updates each ghost’s position based on their dx and dy.
    • The ghosts follow predefined paths and use a scatter mode for a short period.
    • Refer to src/game.ts: src/game.ts