Crafty JS

repository·develop·Indexed 25 days ago

https://github.com/craftyjs/crafty

A modern component and event-based JavaScript game framework targeting DOM, Canvas, and WebGL. Crafty JS utilizes an Entity-Component architecture to handle rendering and DOM interaction, featuring a built-in event system, asset loading (Crafty.load), scene management (Crafty.scene), and a Model component for data isolation and change tracking. Version 0.8.0.

Tokens
5.9K
Snippets
20
Records
34
Agent score
86%

What's inside craftyjs

  1. Initialize and use Crafty JS

    develop

    Crafty JS is a game library that uses an Entity-Component system. You can initialize the game engine using Crafty.init(width, height) and set a background color with Crafty.background(color).

    Entities are created using Crafty.e("Component1, Component2, ..."), where you pass a comma-separated string of components to define the entity's capabilities (e.g., 2D, DOM, Color, Collision).

    Common patterns include:

    • Using .attr({ ... }) to set properties like position (x, y) and dimensions (w, h).
    • Using .bind('UpdateFrame', function() { ... }) to run logic every frame.
    • Using .onHit('ComponentName', function() { ... }) to handle collision events.
    • Using Crafty("ComponentName") to select all entities with a specific component.
  2. Use built-in and custom easing functions in Crafty JS

    develop

    When using components that support easing (such as Tween or SpriteAnimation), you can specify how the animation progresses by providing either a string representing a built-in easing function or a custom function.

    Built-in easing functions include:

    • linear: No acceleration.
    • smoothStep: Starts and ends with velocity 0.
    • smootherStep: Starts and ends with velocity 0 (smoother than smoothStep).
    • easeInQuad: Quadratic curve starting with velocity 0.
    • easeOutQuad: Quadratic curve ending with velocity 0.
    • easeInOutQuad: Quadratic curve starting and ending with velocity 0.

    Custom easing functions must accept a single parameter t (representing progress from 0 to 1) and return the calculated progress between 0 and 1.

    var e = Crafty.e("2D, Tween");
    
    // Use built-in easing functions
    e.tween({x:100}, 1000, "smoothStep");
    e.tween({y:100}, 1000, "easeInQuad");
    
    // Define a custom easing function: 2t^2 - t
    e.tween({w:0}, 1000, function(t){return 2*t*t - t;});
  3. Use the Model component for data isolation and change tracking

    develop

    The Model component allows you to isolate business logic by providing default values, tracking "dirty" (changed) values, and supporting deep events.

    To use it, include this.requires('Model'); in the init function of your custom component.

    Important: To ensure events are triggered correctly, always access and modify data using .get(), .set(), or .attr() rather than accessing properties directly.

    Crafty.c('Person', {
      name: 'Fox',
      init: function() {
        this.requires('Model');
      }
    });
    
    // Usage example
    var person = Crafty.e('Person').attr({name: 'blaine'});
    
    person.bind('Change[name]', function() {
      Crafty.log('name changed!');
    });
    
    person.attr('name', 'blainesch'); // Triggers the event
  4. Animate properties with the Tween component

    develop

    The Tween component allows you to animate numeric 2D properties over time. Supported properties include x, y, w, h, alpha, and rotation.

    To use it, add the Tween component to an entity using Crafty.e("2D, Tween").

    Crafty.e("2D, Tween")
       .attr({alpha: 1.0, x: 0, y: 0})
       .tween({alpha: 0.0, x: 100, y: 100}, 200);
  5. Extend supported image extensions with Crafty.imageWhitelist

    develop

    The Crafty.imageWhitelist is an array of file extensions that Crafty.load recognizes as valid images. You can push new extensions to this list to support additional formats (e.g., tif).

    // add tif extension to list of supported image files
    Crafty.imageWhitelist.push("tif");
  6. Preload game resources with Crafty.load

    develop

    Use Crafty.load(assets, onLoad, [onProgress], [onError]) to preload sounds, images, and sprites.

    Arguments

    • assets: A JSON-formatted object or string defining the assets. Supported top-level keys are audio, images, and sprites.
    • onLoad: Callback function executed when all assets are successfully loaded.
    • onProgress (optional): Callback executed for every asset loaded. Receives an object: { loaded: number, total: number, percent: number, src: string }.
    • onError (optional): Callback executed when an asset fails to load. Receives an object with progress information and the failed asset.

    Asset Formats

    • Audio: Can be a single string (filename) or an array of strings (multiple formats for fallback). If Crafty.support.audio is true, mp3, wav, ogg, and mp4 are supported.
    • Images: An array of filenames.
    • Sprites: An object where the key is the filename and the value defines tile dimensions and a map of component names to coordinates.

    Example

    var assetsObj = {
        "audio": {
            "beep": ["beep.wav", "beep.mp3", "beep.ogg"],
            "boop": "boop.wav"
        },
        "images": ["goodguy.png"],
        "sprites": {
            "animals.png": {
                "tile": 50,
                "tileh": 40,
                "map": { "ladybug": [0,0], "lazycat": [0,1] }
            }
        }
    };
    
    Crafty.load(assetsObj, 
        function() { 
            // Success callback
            Crafty.scene("main");
        },
        function(e) { 
            // Progress callback: e.percent, e.loaded, etc.
        },
        function(e) { 
            // Error callback
        }
    );
    var assetsObj = {
        "audio": {
            "beep": ["beep.wav", "beep.mp3", "beep.ogg"],
            "boop": "boop.wav",
            "slash": "slash.wav"
        },
        "images": ["badguy.bmp", "goodguy.png"],
        "sprites": {
            "animals.png": {
                "tile": 50,
                "tileh": 40,
                "map": { "ladybug": [0,0], "lazycat": [0,1], "ferociousdog": [0,2] },
                "paddingX": 5,
                "paddingY": 5,
                "paddingAroundBorder": 10
            },
            "vehicles.png": {
                "tile": 150,
                "tileh": 75,
                "map": { "car": [0,0], "truck": [0,1] }
            }
        },
    };
    
    Crafty.load(assetsObj, // preload assets
        function() { //when loaded
            Crafty.scene("main"); //go to main scene
            Crafty.audio.play("boop"); //Play the audio file
            Crafty.e('2D, DOM, lazycat'); // create entity with sprite
        },
    
        function(e) { //progress
        },
    
        function(e) { //uh oh, error loading
        }
    );
  7. Switch to a scene with Crafty.enterScene()

    develop

    Use Crafty.enterScene(name, [data]) to immediately switch to a registered scene.

    • name: The name of the scene to run.
    • data: Any type except a function. This is passed as the first parameter to the scene's init function.

    Behavior:

    • Triggers SceneDestroy with { newScene: name }.
    • Resets the viewport.
    • Destroys all 2D entities that do not have the Persist component.
    • Executes the uninitialize function of the current scene if it exists.
    • Triggers SceneChange with { oldScene: String, newScene: String }.
    • Executes the initialize function of the new scene, passing data as an argument.

    Throws an error if data is a function or if the scene name does not exist.

    // Play a scene that was defined to accept attributes
    Crafty.defineScene("square", function(attributes) {
        Crafty.background("#000");
        Crafty.e("2D, DOM, Color")
              .attr(attributes)
              .color("red");
    });
    
    // Enter the scene with specific attributes
    Crafty.enterScene("square", {x:10, y:10, w:20, h:20});
  8. Register a scene with Crafty.defineScene()

    develop

    Use Crafty.defineScene(name, init, [uninit]) to register a scene without playing it immediately.

    • name: The unique string ID for the scene.
    • init: A function executed when the scene is played. It can accept one argument (data).
    • uninit (optional): A function executed before the next scene is played, after 2D entities (without Persist) are destroyed.

    Throws an error if init is not a function.

    Crafty.defineScene("loading", function() {
        Crafty.background("#000");
        Crafty.e("2D, DOM, Text")
              .attr({ w: 100, h: 20, x: 150, y: 120 })
              .text("Loading")
              .textAlign("center")
              .textColor("#FFFFFF");
    });