GMS 2.3+ (RESOLVED) - Spawn objects randomly on grid

Lemmy4K

Member
How would I go about spawning an object multiple times randomly in between a grid across the entire room?

I have an object called ObjTree and I want it to look like the screenshot but repeated throughout the entire room. Pretty much in that same position.
The room is a 32x32 grid.

Can anyone help me out?
 

Slyddar

Member
This will spawn a tree in every grid cell in the room, in the position you have shown, if you have the origin at the bottom middle of the tree. If you have the origin in a different spot, modify the additions to x and y.

Code:
var _w = room_width div 32;
var _h = room_height div 32;
for (var yy = 0; yy < _h; ++yy) {
    for (var xx = 0; xx < _w; ++xx) {
        instance_create_layer(xx + 16, yy + 32, "Instances", ObjTree);
    }
}
If you want to do it randomly, add an "if random(0.5) < 1" check before creating the instance, adjusting the value to increase or decrease the density.
 
Last edited:
Top