-
Notifications
You must be signed in to change notification settings - Fork 4
Containers
Containers are display containers for other game objects.
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();
Containers aren't on the scene update list and don't update their children. Before Phaser v3.60.0, if you've instantiated an updatable game object and added it to a container, you also need to add it to the update list:
const sprite = new Phaser.GameObjects.Sprite(/*…*/);
sprite.addToUpdateList();
container.add(sprite);
When containers are given exclusive = false
, a game object can be added to several of them at once, and each container will render it.
As containers are dimensionless, you should pass a hit area or call setSize()
first.
Without setSize()
(the default), the hit area's (x, y) is placed on the container's (x, y).
With setSize()
, the hit area's (x, y) is placed on the top-left of a (width, height) rectangle centered on the container's (x, y).
Containers and children can be masked, but the mask source (game object) must be outside any container.
You can add a physics body to a container. You should call the container's setSize()
first or use setBodySize()
after.
Container children can also have physics bodies.
Remember that child coordinates are local. The constructor arguments x
y
are for the container itself.
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.