Skip to content

Containers

samme edited this page Feb 1, 2022 · 24 revisions

Sprites in a container

Containers are display containers for other game objects.

Local and world coordinates for a sprite and container

When you add a child game object to a container, the child's x and y values don't change, but they become local coordinates, relative to the container's position. At render time the child is transformed into the container's space and drawn there. The local coordinates (0, 0) map onto the container's own x and y.

Containers are dimensionless, but you can give them an artificial size:

container.setSize(100, 50);

These width and height values and the container's origin (0.5, 0.5) are used for input, physics, and camera culling only. They don't influence child positioning at all. The width and height are initially zero.

You can calculate a container's bounds, the smallest rectangle containing all of its children:

const { left, right, top, bottom, width, height } = container.getBounds();

Non-exclusive containers

A rainbow band twirled through several non-exclusive containers

When containers are given exclusive = false, a game object can be added to several of them at once. Visually it gets duplicated.

Input

As containers are dimensionless, you should pass a hit area or assign a width and height first.

The hit area's top-left (x, y) is always placed on the container's top-left, but if the container has no size then its top-left is identical to its position (x, y).

Masks

Containers and children can be masked, but the mask source (game object) must be outside any container.

Physics

You can add a physics body to a container, but not its children.

For Arcade Physics you should call the container's setSize() first or use setBodySize() after.

Extending containers

Remember that child coordinates are local. The constructor arguments x y are for the container itself.

Alternatives to containers

If several game objects are positioned together only once but never moved thereafter, you don't need a container.

If you need to manage only alpha, blend modes, depth, masks, or visibility together (i.e. no transforms), you can use a layer instead.

If you need to translate (shift) a bunch of same-texture images, a blitter can be used instead.

Particle emitters can be translated, scaled, or rotated via their particle manager instead.

For a scrolling/zooming "window", an extra camera may be a better choice.

Clone this wiki locally