Components#

Components describe individual pieces of an entity's state. They are plain JavaScript objects and don't contain any behavior or logic.

As an example, the $transform component simply stores a position array (x,y), rotation, and scale array (sx,sy).

Creating a Component#

To create a custom component of your own, you first need to create a component factory. A component factory is a function which is used to create individual instances of your component.

As an example, let's re-create the $transform component, which holds a position array, a rotation and a scale array:

import { createComponentFactory } from "gamekit-engine/core/component";

export const $transform = createComponentFactory({
  name: "transform",
  get: (data?: {
    pos?: [number, number];
    rot?: number;
    scale?: [number, number]
  }) => {
    return {
      pos: data?.pos ?? [0, 0],
      rot: data?.rot ?? 0,
      scale: data?.scale ?? [1, 1],
    };
  },
});

In the above example, $transform is a function that can be used to create component objects, as shown below:

const transformInstance1 = $transform(); // { pos: [0, 0], rot: 0, scale: [1, 1] }
const transformInstance2 = $transform({ pos: [9, 2] }); // { pos: [9, 2], rot: 0, scale: [1, 1] }

Below is a table of all createComponentFactory options:

Argument Desription Required
name Name of the system Yes
get Function which returns individual component instances Yes
deps Other component factories which the component depends on No
singleton Indicicates that the component is a singleton. Defaults to true No

Component Dependencies#

Sometimes, a component may require another component to function properly. As an example, rendering a sprite image requires knowing its position, rotation and scale. It then makes sense that the $sprite component depends on the $transform component.

This relationship can be specified in a call to createComponentFactory as shown below:

export const $transform = createComponentFactory(/* ... */);

export const $sprite = createComponentFactory({
  name: "sprite",
  /*...*/
  deps: [$transform],
});

So an entity which includes the $sprite must also include the $transform component.

import { createEntity } from "gamekit-engine/core/entity";

const entity1 = createEntity("player", [$sprite({ src: "" })]); // ❌ Error! $sprite requires $transform
const entity2 = createEntity("player", [$sprite({ src: "" }), $transform()]); // ✅ Works

Singleton Components#

The $transform component contains an entity's position, rotation and scale. So it makes sense that an entity should have only one $transform instance.

An entity can however have multiple $sprite components since it may need to render multiple part images.

By default, createComponentFactory marks all component factories as singletons. A singleton component cannot have multiple instances on an entity.

If your component can have multiple instance on an entity, specify it like so:

export const $transform = createComponentFactory({
  name: "transform",
  /*...*/
});

export const $sprite = createComponentFactory({
  name: "sprite",
  /*...*/
  singleton: false,
});

In the above snippet, $transform becomes a singleton component, however $sprite is not, and an entity can have multiple instance of it.

import { createEntity } from "gamekit-engine/core/entity";

const entity1 = createEntity("player", [$transform(), $transform()]); // ❌ Error! $transform is a singleton, cannot have multiple instances
const entity2 = createEntity("player", [$transform(), $sprite({ src: "img1.png" }), $sprite({ src: "img2.png" })]); // ✅ Works

Builtin Components#

GameKit ships a number of built-in components which we'll explore here.

$metadata#

Creates a metadata component for an entity.

import { $metadata } from "gamekit-engine/core/prefabs";

const metadata = $metadata({
  id: string,           // Id string (Required)
  description: string,  // Description string (Optional)
  tags: string[],       // Tag list (Optional)
  categories: string[], // Category list (Optional)
});

$transform#

Creates a transform component for an entity. This contains position, rotation and scale data.

import { $transform } from "gamekit-engine/core/prefabs";

const transform = $transform({
  pos: [number, number],    // Position (Optional)
  rot: number,              // Rotation (radian, clockwise) (Optional)
  scale: [number, number],  // Scale (Optional)
})

$sprite#

Creates a sprite component for an entity. This contains data used to render an image.

import { $sprite } from "gamekit-engine/core/prefabs";

const sprite = $sprite({
  src: string                             // Relative path to image file from the `src/assets` directory (Required)
  size: [number, number],                 // Dimensions of rendered sprite (Optional)
  offset: [number, number],               // Offset of image from center (Optional)
  layer: number,                          // Index of layer on which to draw image (Optional)
  flip: false | "x" | "y" | true,         // How to flip the image (Optional)
  crop: [number, number, number, number], // Crop bounds (x, y, w, h) (Optional)
  opacity: number,                        // Opacity of the image (Optional)
});

$animatedSprite#

Creates an animated sprite component for an entity. This contains data used to render a spritesheet animation.

import { $animatedSprite } from "gamekit-engine/core/prefabs";

const animatedSprite = $animatedSprite({
  src: string                   // Relative path to image file from the `src/assets` directory (Required)
  size: [number, number],       // Dimensions of rendered spritesheet (Required)
  cell: [number, number],       // Dimensions of each sprite in the sheet (Required)
  durationMs: number,           // Duration in milliseconds of the entire animation (Required)
  loop: boolean,                // Indicates if the animation should loop continuously (Optional)
  offset: [number, number],     // Offset of animation from center (Optional)
  layer: number,                // Index of layer on which to draw image (Optional)
  opacity: number,              // Opacity of the animation (Optional)
});

$audioSource#

Creates an audio source component for an entity. This contains data used to play audio for an entity.

import { $audioSource } from "gamekit-engine/core/prefabs";

type AudioEffect =
  | { id: string; type: "delay"; delayTime: number }
  | { id: string; type: "gain"; gain: number }
  | { id: string; type: "lowpass"; cutoff: number }
  | { id: string; type: "highpass"; cutoff: number }
  | { id: string; type: "bandpass"; minCutoff: number; maxCutoff: number }
  | { id: string; type: "reverb"; damping: number; mixRatio: number };

type Spatialization = {
  minDistance: number;            // Minimum distance from the audio listener at which the playback is at max volume
  maxDistance: number;            // Maximum distance from the audio listener at which the playback is effectively muted
  falloff: "lin" | "log" | "exp"; // Curve function to use for falloff computation */
}

const audioSource = $audioSource({
  src: string,              // Relative path to audio file from the `src/assets` directory (Required)
  loop : boolean,           // Indicates if playback should restart when it ends (Optional)
  autoplay : boolean,       // Indicates if the playback should start automatically (Optional)
  volume : number,          // Normalized volume (Optional)
  speed : number,           // Normalized playback speed (Optional)
  channelId : string,       // Id of channel to attach to the playback (Optional)
  effects : AudioEffect[],  // List of audio effects to apply to the playback (Optional)
  spatial : Spatialization, // Spatialization settings of the playback (Optional)
  onend : () => void,       // Callback for when the playback ends (Optional)
});

Next Steps#

In the next guide, we'll explore entities in more detail and see their relation to components.