๐Ÿงฉ SpriteComponent

The SpriteComponent is used to render 2D images and sprite sheets in your game. It supports positioning, scaling, rotation, flipping, transparency, and sprite sheet animations.

๐Ÿ“ฆ Import

js
import { SpriteComponent } from "kernelplay-js";

โš™๏ธ Usage

Attach it to an entity to display an image:

js
entity.addComponent("renderer", new SpriteComponent({
  image: "./assets/player.png",
  width: 64,
  height: 64
}));

๐Ÿงพ Properties

๐Ÿ–ผ๏ธ Image

  • image (string | Image)
    Path to the image or an already loaded Image object.

๐Ÿ“ Size

  • width (number) โ€“ Render width
  • height (number) โ€“ Render height

๐ŸŽž๏ธ Sprite Sheet

  • sourceX (number) โ€“ X position inside the sprite sheet
  • sourceY (number) โ€“ Y position inside the sprite sheet
  • sourceWidth (number) โ€“ Width of a frame
  • sourceHeight (number) โ€“ Height of a frame

๐Ÿ‘‰ If sourceWidth or sourceHeight is not set, the full image is used.

โš“ Anchor (Pivot)

  • anchor ({x, y})

Controls the origin point of the sprite:

markdown
| Value | Meaning |
|------|--------|
| `{x: 0, y: 0}` | Top-left |
| `{x: 0.5, y: 0.5}` | Center (default) |
| `{x: 1, y: 1}` | Bottom-right |

๐Ÿ”„ Flip

  • flipX (boolean) โ€“ Flip horizontally
  • flipY (boolean) โ€“ Flip vertically

๐ŸŽจ Appearance

  • alpha (number) โ€“ Transparency (0 to 1)
  • tint (string) โ€“ Color tint (optional)

๐Ÿงฑ Layering

  • zIndex (number) โ€“ Controls render order

๐ŸŽž๏ธ Sprite Sheet Example

js
const sprite = new SpriteComponent({
  image: "./assets/player_sheet.png",
  sourceWidth: 64,
  sourceHeight: 64,
  width: 50,
  height: 50
});

๐ŸŽฌ Changing Frames

Use setFrame() to display a specific frame from a sprite sheet:

js
sprite.setFrame(64, 0, 64, 64);

๐Ÿ” Flip Example

js
sprite.flipX = true; // Mirror character

๐Ÿ‘ป Transparency Example

js
sprite.alpha = 0.5; // 50% transparent

๐ŸŽฏ Full Example

js
entity.addComponent("renderer", new SpriteComponent({
  image: "./assets/player_sheet.png",
  sourceWidth: 64,
  sourceHeight: 64,
  width: 50,
  height: 50,
  anchor: { x: 0.5, y: 0.5 },
  alpha: 1,
  flipX: false,
  zIndex: 10
}));

๐Ÿ’ก Tips

  • Use sprite sheets for animations (with an animator system)
  • Keep anchor at {0.5, 0.5} for easier rotation
  • Match sourceWidth/Height with your sprite sheet grid
  • Use flipX instead of separate left/right sprites