game-maker-studio-2

How would I randomize where sprites appear on the screen in GameMaker?


I am making a shooter in which enemies (sprite) come into the game from random locations in the game window at a pre-set rate. I was wondering how I could do this in GameMaker 2.

I am able to make them appear at fixed locations, but am unable to figure out how to make the location random within a given boundary.


Solution

  • First off: Don't use just sprites for enemies, as sprites are just the image without functionality behind. If you want to add functionality to a sprite, then use objects instead (and assing a sprite to that object).
    GameMaker is Object-oriƫnted, so understanding objects is a core mechanic to understand it's functionality.

    Once you have an object, then use a random() value

    With this, you can set a value to set a value of which random number it should make, between 0 and the value you set. (If you want to use a different minimal value, use random_range(). )

    For example in the Create Event:

    var randomx = random(100); //this will choose a random decimal number between 0 and 100
    x = randomx;
    y = 0;
    

    The value I filled in is 100, but in your case, it should be the maximum width of your game screen.

    You can then continue to use that randomx for the x position where you spawn your enemies. (and then set the y position to 0 to make them appear on top of the screen)

    This random number will be a decimal, though that's not important in your scenario, but keep it in mind when you want to compare a random number with an integer number, that it'll need to be rounded first.

    Source: https://manual.yoyogames.com/GameMaker_Language/GML_Reference/Maths_And_Numbers/Number_Functions/random.htm