Advertisement
Badwrong

GameMaker - Alpha Mask Layer

Oct 20th, 2022 (edited)
2,945
2
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     The following shows how to create an alpha mask using layer scripts.
  3.     In this solution the background will be preserved and anything drawn by masked areas will still show the background.
  4.  
  5.     Setup:
  6.     1. Leave the background alone.
  7.     2. Create layers with the following names and  the order should look the same in the room editor:
  8.         [ hidden_end ] - Any layer type, as this just execute the end script.
  9.         ...optional layers that will also be alpha masked
  10.         [ hidden_start ] - Asset or object layer.  Things can be placed here and will be hidden if overlapping with alpha masked areas.
  11.         [ alpha_mask ] - Asset layer where you place sprites to define the alpha masked area.
  12.         [ Background ] - Default background layer.
  13.     3. Place the following code in an object that is created when the room begins, or simply place it an objects "room start" event.
  14. */
  15.  
  16. // ************* Layer scripts for alpha masking **************** //
  17.  
  18. layer_script_begin(layer_get_id("alpha_mask"),
  19.     function() 
  20.     {
  21.         if (event_type != ev_draw || event_number != 0) return;
  22.            
  23.         // Alpha test ensures the background isn't erased and we can use any shapes
  24.         gpu_set_alphatestenable(true);
  25.         gpu_set_alphatestref(200);
  26.  
  27.         // Mark areas with 0 alpha
  28.         gpu_set_blendmode_ext_sepalpha(bm_zero, bm_one, bm_zero, bm_zero);
  29.     });
  30.  
  31.  
  32. layer_script_begin(layer_get_id("hidden_start"),
  33.     function()
  34.     {
  35.         if (event_type != ev_draw || event_number != 0) return;
  36.                
  37.         // Cannot draw on areas with 0 alpha
  38.         gpu_set_blendmode_ext_sepalpha(bm_dest_alpha, bm_inv_dest_alpha, bm_dest_alpha, bm_one);
  39.     });
  40.    
  41. layer_script_end(layer_get_id("hidden_end"),
  42.     function()
  43.     {
  44.         if (event_type != ev_draw || event_number != 0) return;
  45.  
  46.         gpu_set_alphatestenable(false);
  47.        
  48.         // Flip the alpha channel back to 1
  49.         gpu_set_blendmode_ext_sepalpha(bm_dest_colour, bm_zero, bm_one, bm_zero);      
  50.         var _cam = camera_get_active();
  51.         draw_rectangle_color(
  52.             camera_get_view_x(_cam),
  53.             camera_get_view_y(_cam),
  54.             camera_get_view_width(_cam),
  55.             camera_get_view_height(_cam),
  56.             c_white, c_white, c_white, c_white, false
  57.         );     
  58.        
  59.         // Back to normal
  60.         gpu_set_blendmode(bm_normal);
  61.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement