r/gamemaker • • 9d ago

Help! Help with Randomly Spawning Enemies

Hi all, I am really new to learning Gamemaker, so far mostly just watched a couple of tutorials and am experimenting with stuff. I am trying to make a very basic game where you just move around a room and kill enemies that randomly spawn in just to get a handle on how to do these things.

I seem to have figured out how to make enemies randomly spawn in but was having an issue with them spawning inside walls and am having trouble figuring out how to not do that.

This is what I came up with as a quick and dirty way but it basically only works with the current room I am working in, so not something that can be easily reused

if (instance_number(obj_enemy) < max_spawns)

{
var _rx = irandom_range(411, 914);

var _ry = irandom_range(173, 561);

instance_create_layer(_rx, _ry, "Instances", obj_enemy);

}

Can anyone help me with a way to make something cleaner and resuable that prevents the enemies from spawning in walls or on top of each other?

Thank you in advance.

2 Upvotes

11 comments sorted by

2

u/Lethalogicax 9d ago

I'm not sure what your exact setup is, but there are a few different ways of approaching this...

You can make your placement algorithm intelligently find valid locations before spawning (might be difficult, will definitely be a lot of math), or you could make the spawn mechanic fail when choosing an invalid spot so it rerolls RNG and tries again in a new spot (quick and dirty solution).

Either way, you need to find a way to detect when an object has been placed into an invalid location and then have your code reject the invalid location, and to then select a new random location.

Are you using Gamemaker's built-in collision system? If so then you can use place_meeting() to detect if a set of coordinates is within an object's hitbox.

1

u/nanaki626 8d ago

I am using the built in collision system at the moment, as it seemed the easier thing to do, and like I said, REALLY new at this.

How would I put place_meeting() into my code?

2

u/Lethalogicax 8d ago

I'll be real with you, I don't touch the built-in collision functions, so I'm super unfamiliar with them (I literally wrote my own collision engine in my game because reasons). I'm really not exactly sure. I can explain the theory a little bit, but due to my own personal limitations I am going to be unable to write any helpful code...

So place_meeting(x,y,z) is going to be taking 3 arguments. Arguments are the values that are seperated by a comma in the brackets following place_meeting.

Calling this function from an object is going to move the object that called it to the target location that is specified in the x and y arguments. It's going to check for a collision with the specified object that was in the 3rd argument(z). Then it's going to immediately move back to where it was before. This function then returns true or false depending on whether a collision is found.

What is meant by "the function returns true or false" is that calling place_meeting(x,y,z) is going to output a boolean result when it runs. So if you put something in your code like...

if place_meeting(target_x,target_y,ob_sample) { show_debug_message("hello world"); }

...then place_meeting is going to be either true or false and in this case a true output will show a debug message. But you can put whatever you want between those curly braces, even nesting more expressions inside! If a collision is found, then the program is interpretting it as...

if (true) { show_debug_message("hello world"); }

...and the true result causes the code inside the brackets to be executed! If there is no collision, the program would read it as if (false) { } and the false result would mean that the code inside the curly brackets will be skipped over by the engine.

You can then use that to figure out if you've got a collision between those 2 objects and use that result to choose whether or not to move the object to the target location. Something like:

if !place_meeting(target_x,target_y,ob_sample) { x = target_x; y = target_y; }

In this case, the "!" in front of place meeting is a NOT modifier. Adding a ! to the front of an expression like this, specifically one that returns true or false, reverses it. True becomes false, false becomes true. So here we are saying if there is NOT a collision between these 2 instances, then change the x and y coordinates to the target location. This results in movment only occuring when no collision is detected. However, you'll soon find out that it gets a little bit more complicated then that. What happens when an object is 4 pixels away from a solid object and is trying to move at a speed of 5? It's going to try to test collision at that location 5 pixels away, see that it causes a collision, and returns false. This results in your character object being stuck a few pixels away from the wall and unable to move flush against the wall. This is where the collision system needs to get more granular to permit only the valid portion of the movement. But leave that as an exercise for another day. Your job right now is to make your object refuse to collide with the other object, and without getting overlapping hitboxes that get stuck together!

If you have more questions, fire away! I'll try to help out as much as I can.

2

u/nanaki626 7d ago

Thanks a lot!

That seems to have done the trick. Have run the program a couple times now and nothing is spawning in the walls. They are sometimes spawning right next to the walls and getting stuck, so now I need to figure that out. I think it could be something with the sprites themselves, I am using ones from a tutorial because my artistic skills are somewhat lacking and the moment. So gonna try playing around with those and seeing if fixes the problem.

2

u/JaXm 9d ago edited 9d ago

You can do something like 

function spawn_enemy() {
    var _rx = irandom_range(411, 914);
    var _ry = irandom_range(173, 561);

    while (collision_point(_rx, _ry, obj_wall) {
        
        _rx = irandom_range(411, 914);
        _ry = irandom_range(173, 561);
    }
    
instance_create_layer(_rx, _ry, "Instances", obj_enemy);
}

What this does is it runs a while loop, and if rhe randomly selected coordinates return a collision, will find new coordinates until they no longer do, THEN, create rhe enemy at those coordinates. 

Then you just call the function somewhere in your code whenever you want to spawn in a new enemy. 

Edit: corrected using the wrong collision function check. 

1

u/nanaki626 8d ago

Hmm, I don't have an obj_wall or anything like that at the moment. At the moment been using move_and_collide with a tile layer to stop movement through walls rather than having walls be their own object.

1

u/JaXm 8d ago

Well, you'll have to figure out that part on your own. The overall point is to get the code to say "hey, i esnt to soawn a bad guy here. is this a good place to spawn a baddie?" And if the answer is "no" to then check somewhere else until the answer is "yes". Whatever that looks like in YOUR code, will be different. 

But the logic will be the same. 

1

u/Majestic-Singer7503 9d ago

Sbagliato. Non puoi valutare una collisione in un solo punto. L'istanza potrebbe collidere anche se il singolo punto non lo fa. Ci sono funzioni dedicate alle collisioni, una di queste è place_meeting  Sono un po' arrugginito quindi non mi ricordo quali sono le altre, consiglio a op di guardare sul manuale e di non usare assolutamente il codice che ti è stato dato qua sopra.

1

u/azurezero_hdev 9d ago

you cant prevent them from spawning on walls, but you can have them rapidly jump around on creation until they find an empty space (with a while statement)

1

u/azurezero_hdev 9d ago

while !place_free(x,y) or place_meeting(x,y,obj_enemy){

x = whatever
y = whatever
}

1

u/Krilantis 9d ago

Test the spawn with the enemy's own mask rather than a single point: create it, then `with (_e) { if (place_meeting(x, y, [obj_wall, obj_enemy])) instance_destroy(); }` and retry. That catches both walls and other enemies (the array form needs a recent GameMaker version). Put a cap on the retries, like 10 per spawn, so a crowded room can't hang in a while loop, and use room_width/room_height or a spawn-area object instead of hardcoded ranges so it's reusable across rooms.