Search code examples
game-maker

Making objects avoid spawning on top of one another


As the title suggests, does anyone know the correct way to keep objects that continually re-spawn (currently set to a random position on the x axis) from spawning on top of one another, in game-maker?


Solution

  • You can add a check to the Create event of your respawning object which uses place_meeting(x,y,object_index) to check if it intersects another instance of the same object type. If so, you could try setting another position.

    You could also do this in the code which spawns your instances, by first creating the instance and then testing random locations until you find a good one:

    newinst = instance_create(0,spawnY,object0);
    with(newinst) {
        var tries, done;
        tries = 0;
        done = false;
        do {
            tries += 1;
            x = irandom(room_width);
            done = !place_meeting(x,y,object_index);
        } until(done or tries>50);
        if(not done) {
            // not enough space (or bad luck), bail out
            instance_destroy();
        }
    }
    

    The "tries" limit is meant to prevent running into an infinite loop if no space is available. This method is not efficient if you expect that most space will be taken, and it can fail while there is actually still room available (also more likely if there are already many instances blocking the way), if this is a problem you need a more elaborate system. However, if you expect that there will usually be plenty of space for your critters to spawn, this should be good enough.