Instantiation of Objects

What is instantiation?

Instantiation means creating a new instance (copy) of an object from a class blueprint. Each instance has its own properties and data.

Benefits of instantiation?

  • Create multiple objects with same structure
  • Each object maintains its own data
  • Efficient way to create similar objects
  • Organize objects into classes
  • Build game entities from templates

Benefits of Instantiation & Objects

-Reusability - Create many objects from one blueprint without rewriting code

  • Organization - Keep related data and methods together
  • Easy to manage - Each object has its own properties and state Scalability - Add new objects easily without breaking existing code
import GameEnvBackground from '@assets/js/GameEnginev1/essentials/GameEnvBackground.js';
import Player from '@assets/js/GameEnginev1/essentials/Player.js';
import ExampleEnemy from '@assets/js/projects/collisions-mechanic/levels/ExampleEnemy.js';

class GameLevelCollisionMechanicsLessonLevel {
    constructor(gameEnv) {
        const path = gameEnv.path;

        // Create configuration data for the background
        const bgData = {
            name: "custom_bg",
            src: path + "/images/gamebuilder/bg/alien_planet.jpg",
            pixels: { height: 772, width: 1134 }
        };

        // Create configuration data for the player
        const playerData = {
            id: 'playerData',
            src: path + "/images/gamebuilder/sprites/astro.png",
            SCALE_FACTOR: 5,
            INIT_POSITION: { x: 100, y: 300 },
            // ... more properties
        };

        // Create configuration data for an enemy
        const npcData = {
            id: 'ufo',
            src: path + "/images/gamebuilder/sprites/ufos.png",
            SCALE_FACTOR: 8,
            INIT_POSITION: { x: 259, y: 223 },
            // ... more properties
        };

        // Instantiate all game objects
        this.classes = [      
            { class: GameEnvBackground, data: bgData },
            { class: Player, data: playerData },
            { class: ExampleEnemy, data: npcData }
        ];
    }
}

export default GameLevelCollisionMechanicsLessonLevel;

What does this do?

  1. Import Classes - First, you import the classes you want to use
  2. Create Data Objects - Define the properties for each object (bgData, playerData, npcData)
  3. Instantiate - In this.classes, you create actual instances of each class with their specific data
  4. Store References - Each object is stored so the game engine can manage them

Try It Yourself

%%js // CODE_RUNNER: instantiation-objects class Weapon { constructor(name, damage) { this.name = name; this.damage = damage; } } const sword = new Weapon(“Sword”, 50); const bow = new Weapon(“Bow”, 35); console.log(sword.name, sword.damage); console.log(bow.name, bow.damage);