How to add spoiler tags, edit posts, add images etc. How to - a user's guide to the new version of Boards
Mods please check the Moderators Group for an important update on Mod tools. If you do not have access to the group, please PM Niamh. Thanks!

Game Maker: Setting a random spawn with limits

  • #1
    Registered Users Posts: 101 ✭✭ PKdude

    Hey guys, I am currently on the finishing touches for my Spaceship game. I have it so that various enemies follow the player ship wherever he goes. I have them spawn at a random range when they get destroyed, however, they will sometimes spawn right beside or on top of the player. I have been trying to figure out how to limit this but I am still unsure and unable to do it. Would someone be able to help me?
    Here is the code for my spawning. It is in the Step Event for the Game Controller:
        l = 700;
        x = obj_player.x + random_range(-l, l);
        y = obj_player.y + random_range(-l, l);
        instance_create(x,y, obj_enemy)
        instance_create(0, 0, obj_enemy)

    Thanks for taking the time to look, and have a nice day :3


  • x = obj_player.x + random_range(-l, l);
    y = obj_player.y + random_range(-l, l);

    I'm not familiar with GameMaker, but if random_range() gives you an integer rather than a float, then there's a 1 in 3 chance that it will give you 0.

    So it's a 1/9 chance that they will both be 0, meaning the enemy you're creating's X and Y will be the same as the players.
    x = obj_player.x + 0;
    y = obj_player.y + 0;

    EDIT, read it wrong and thought it was a range between 1 and -1 instead of L and -L. Theory's still the same, just with much less likely odds. (1 in 490,000 that you'll get 2 0s). What you'd need is a minimum distance and maximum distance at which an enemy can spawn, then multiply by a range of 1 and -1 (removing any 0s that come up)
    minDist = 400;
    maxDist = 700;
    xSign = random_range(-1,1);
    ySign = random_range(-1,1);
    if(xSign = 0)
    [COLOR="Lime"][COLOR="YellowGreen"]//You have 2 choices here, you can either try to get another random number again but that would require putting this into a method which I don't know how to do in GML
    //Or you can just give it a value, adds a bias to the result but it should be fine for a small game.
    //I'll just give it a value.[/COLOR][/COLOR]
    xSign = -1;
    if(ySign = 0)
    ySign = 1;
    x = obj_player.x + (random_range(minDist, maxDist) * xSign);
    y = obj_player.y + (random_range(minDist, maxDist) * ySign)

  • Awesome dude, thanks so much! I had a lot of trouble trying to solve this but this has helped loads, thank you kindly!