Introducing Dragonfly Cloud! Learn More

Question: How do you manipulate the z index of instances in GameMaker?

Answer

In GameMaker, the "z index" or depth of an instance determines its drawing order on the screen. Instances with lower depths are drawn on top of those with higher depths. Here's how you can manipulate it:

Setting Depth

You can set the depth of an instance directly using the depth variable in the object's Create Event or at any point within its events like this:

// Set the depth to -100 to draw the instance above others depth = -100;

Changing Depth Dynamically

At runtime, you might want to change an instance's depth based on certain conditions. You can assign a new value to depth whenever needed:

// If the player collects a power-up, bring them to the front if (powerUpCollected) { depth = -50; }

Sorting Instances by Depth

If you have multiple instances that need to be sorted dynamically, you might use instance_create_layer() function and specify the layer, which inherently controls depth:

var inst; inst = instance_create_layer(x, y, "InstancesLayer", obj_Enemy); // "InstancesLayer" is the name of the layer where the instance will be created.

Layers are the preferred method for managing depth since GameMaker Studio 2. Layers have their own depth values and instances placed on a given layer will be rendered according to the layer's depth.

Adjusting Layer Depth

To adjust the depth of an entire layer and thus affect all instances on that layer, you can use:

layer_set_depth("InstancesLayer", -100);

This will move the whole layer "InstancesLayer" above other layers with a higher depth value.

Conclusion

Manipulating depth directly on instances is simple, but working with layers provides a more powerful and organized way to manage rendering order in your game. Use layers when possible for better control over what gets drawn first.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.