Game Development Reference
In-Depth Information
Snap To Grid
If your game is made up of a fixed grid in which instances need to be placed, you may require the
mouse to snap to these positions—either to help the player place game elements in the right
places, or to facilitate a level editor. In the following example, we'll make the mouse snap to a
32x32 grid to place wall objects in the room.
Start with: Reference/Framework/explorer1.gmk
Creating Grid Snapping
1. Create a new object obj_wall and give it the sprite spr_wall . This is the instance we'll
be placing around the room.
2. Create a new object obj_gridcursor and and set the Sprite to spr_gridcursor . Set the
Depth to -10 to make sure it appears in front of everything else.
3. Add a Step event and include a Jump to Position action. For X specify mouse_x , for Y
specify mouse_y . The system variables mouse_x and mouse_y keep track of where the
Windows mouse cursor is within the room.
4. In the same event, include an Align to Grid action. Our grid has squares measuring
32x32, so set Snap hor to 32 and Snap vert also to 32 .
5. Open the Global Game Settings , Graphics tab and remove the check for Display the
cursor . We have our custom cursor now, so we should hide Windows' mouse cursor.
All this is enough to snap the instance to the grid—the next steps are only required to
for instance placement and removal.
6. Open obj_gridcursor again and add a Mouse , Global Left Button event. We're using
the global rather than the regular left button event, because the latter looks for a
collision of the Windows mouse pointer with obj_gridcursor , which is neither
necessary nor always the case. We're also not using a press or release event because we
wish to be able to drag the mouse, painting the room with wall instances. Insert a
Check Object action and select obj_wall for the Object . Check the Relative and NOT
boxes—this checks if there is a collision with obj_wall in the current (snapped)
position, because we only want to place a wall instance if there wasn't one already.
7. Just below it, insert a Create Instance action for obj_wall . Check the Relative box and
don't change the values. It will use the snapped coordinates of obj_gridcursor to place
the wall instance.
8. Now add a Collision event for obj_wall and include a Check Mouse action. Set the
Button to right .
9. In the same event, add a Destroy Instance action and set Applies to to Other . You can
now right-click on a wall object to have it removed again.
10. Because deletion is based on collision detection, it's a good idea to make sure the
sprite cursor is as large as a grid square; otherwise, it may not be able to delete smaller
objects. Open spr_gridcursor and uncheck the Precise collision checking box.
11. Finally, open room_test and place an instance of obj_gridcursor in the room.
Result: Reference/Result/snap_to_grid.gmk
 
 
Search WWH ::




Custom Search