Search code examples
gmlgame-maker-studio-2

How to convert a tile layer into an object for depth sorting relative to the player?


I'm essentially making a Stardew Valley clone, using tile sets and tile layers to draw the background of each room. I have a 'Parent Depth Object'. Each child of this object (NPC's, crops) has its depth sorted relative to the player object to appear in front or behind the player. This works fine.

I have 'ground items' (barrels, rocks etc.) drawn to a single tile layer in each room. I want the player to be able to appear behind or in front of these too. Is there any way I can make this whole layer act as if it was a single object so I can add it to my Parent Depth Object, or do I have to create a separate object for each ground item?

My 'depthSorter' object creates a Data Structure, adds each instance to it and loops through, sorting the depth of each relative to the player.


/// @description DSGridGetInst/Add/Sort/Loop

// get number of instances of parentDepthObject, save in variable instNum / resize grid
var instNum = instance_number(parentDepthObject);
var dGrid = dsDepthGrid;

ds_grid_resize(dGrid, 2, instNum);

// add instances to grid / have all of them run this code
var yy = 0; with(parentDepthObject)
{
    dGrid[# 0, yy] = id;
    dGrid[# 1, yy] = y;
    yy += 1;
}

// sort the grid in ascending order (lowest y value at top)
ds_grid_sort(dGrid, 1, true);

// loop through the grid and draw all the instances

var inst; yy = 0; repeat(instNum)
{
    // pull out an ID
    inst = dGrid[# 0, yy];
    // draw yourself
    with(inst)
    {
        event_perform(ev_draw, 0);
    }

    yy += 1;
}


Solution

  • I'd personally recommend to use these items you want to get behind as objects, rather than tiles. Tiles can't contain a script themselves. So that gets more tricky to use them the way you want.

    However, you don't need to create a new object for each 'ground item'. Instead, you can make an object called 'ground item', and change the sprite / related code to that object.

    For example, when selecting an object in a room, you can use 'Creation Code' to add code that's unique for that object. That way, you can change the sprites of the ground item to it's unique id.

    Another example is to make an object that's a child of the parent 'ground object'. So each object has it's own sprite, but reuses the object from 'ground object'