Game Development Reference
In-Depth Information
Mouse Aim-and-Fire
A must-have feature in any shooter: aim your mouse at your hapless target and fire away, while
your other hand is controlling your movement on the keyboard. Almost all 3D first-person
shooters have this feature, and some 2D games have it too. In our spaceship example, we'll
mount a cannon on top of the ship and make it aim and fire at the mouse position.
Start with: Reference/Framework/spaceship5.gmk
To Create Mouse Aim-and-Fire
1. First, open spr_cannon and set the Origin to ( 10 , 15 ). The cannon will be rotated around
this point.
2. Create a new object called obj_bullet and set spr_bullet as its Sprite .
3. Add an Other , Outside Room event and include a Destroy Instance action.
4. Now create an object called obj_cannon and set spr_cannon as its Sprite .
5. Add a Step , Step event and include a Set Variable action with Variable image_angle
and Value point_direction(x,y,mouse_x,mouse_y) . This function gives us the angle
between the cannon's current position and the position of the mouse, and turns the
sprite's image accordingly.
6. Add a Mouse , Global Left Pressed event. It is important to use a global mouse event
because the player will not be clicking on his own ship when firing. Include a Create
Moving action and set Object to obj_bullet . Set X to lengthdir_x(18,image_angle)
and Y to lengthdir_y(18,image_angle) . Set Speed to 10 , Direction to image_angle , and
check the Relative box. This creates a moving bullet instance in the direction the
cannon sprite is facing, 18 pixels from the cannon's center.
7. Include a Play Sound action and set the sound to snd_shoot . The cannon is almost
done but we still need to keep it fixed on the spaceship.
8. Because the cannon should only exist if there is a spaceship, we make the spaceship
responsible for creating the cannon. Open obj_spaceship and click on the Create
event. Include a Create Instance action and select obj_cannon as the Object . You can
ignore the other parameters.
9. The cannon should also disappear when the spaceship is destroyed. Add a Destroy
event and include a Destroy Instance action. Select Object and set it to obj_cannon .
10. Now we need to make sure the cannon follows the spaceship around. Open obj_cannon
again and add a Step , End Step event. It's important to use the End Step event because
we need to make sure the ship's position has been updated before we move the
cannon there! Include a Jump to Position event and set X to obj_spaceship.x and Y to
obj_spaceship.y . Note that the cannon's origin is set to the ship's origin, which means
it will automatically be placed on the right spot.
Result: Reference/Result/mouse_aim_and_fire1.gmk
 
 
Search WWH ::




Custom Search