Why, and HOW to Use Macros in Gamemaker Studio 2
If you have ever used Gamemaker Studio 2 before, you’ve probably heard of macros before. In this article, you’ll learn why, and how to use macros in Gamemaker Studio 2.
So, why would you even want to use macros in Gamemaker? Macros help clean up your code quite a bit. For example, instead of writing the lengthy function
mouse_check_button_pressed(mb_left) every time you wanted to check if the user is clicking the left mouse button, you could create a macro called
left_pressed. This would shorten your code quite a lot, making it much easier to read.
Think of macros as little “mini scripts”. A macro will execute any script or function you assign it to. Let’s go back to the previous example. We want to create a macro called “left_pressed” which runs the following function:
mouse_check_button_pressed(mb_left). We would set up the macro like so:
#macro left_pressed mouse_check_button_pressed(mb_left)
Notice how there is no or semicolon. This is because if there was a semicolon, the computer would read that line of code as ending there, causing an error. Additionally, there is no equals sign. This is because if there was, the computer would read your code as
[your code] EQUALS [macro]. This, obviously, is not what we want. These are the most common mistakes made when using macros.
Macros are laid out like so:
#macro [macro name] [function to execute]
Note: Macros should only be initialized once. If you try to initialize a macro more than once, you will run into an error.
The following macros are staple in many developer’s projects:
// Camera and view macros #macro cam view_camera #macro base_width 800 #macro base_height 400 #macro win_w window_get_width() #macro win_h window_get_height() #macro disp_w display_get_width() #macro disp_h display_get_height() #macro gui_w display_get_gui_width() #macro gui_h display_get_gui_height() #macro view_x camera_get_view_x(cam) #macro view_y camera_get_view_y(cam) #macro view_w camera_get_view_width(cam) #macro view_h camera_get_view_height(cam) #macro view_r (view_x+view_w) #macro view_b (view_y+view_h)
In conclusion, macros should definitley be a staple in your code. Macros can clean up your code a lot, making it easier to read and maintain.