In this lesson we:
We want to create a projectile fired from the player that moves towards the mouse. The projectile will have a mazimum range and collide with walls and enemies.
Lets create an obj_projectile to represent the projectile.
When the player presses the left mouse button, the projectile will fire towards the mouse. For this, lets add the Global Left Mouse Released event to obj_player. Be careful you do not use Left Mouse Released since this requires the mouse to be over the player instance.
Begin the block of code with a comment describing the intent, utilizing the /// @description tag when description applies to the entire event. The condition for this action is already considered with the use of the mouse event.
/// @description Fire projectile towards mouse
Lets define how we will fire the projectile. We want to create the projectile outside of the player since that logically makes sense, and it should be rotated towards the mouse. We seperate out the stats - such as projectile speed - to make it easier to create different options.
/// @description Fire projectile towards mouse
// Create projectile outside of player towards mouse
// Set projectile stats
How we will do the first part is pretty involved, so lets break down further.
/// @description Fire projectile towards mouse
// Create projectile outside of player towards mouse
// Determine the direction
// Determine location outside of player along the direction
// Create projectile towoards direction
// Set projectile stats
Finally, fill in the methods with GameMaker syntax.
/// @description Fire projectile towards mouse
// Create projectile outside of player towards mouse
// Determine the direction
var dir = point_direction(mouse_x, mouse_y)
// Determine location outside of player along the direction
var start_x = x + length_dir_x(sprite_widith, dir)
var start_y = y + length_dir_y(sprite_height, dir)
// Create projectile towoards direction
var Projectile = instance_create_layer("Instances", startc_x, start_y, obj_projectile)
Projectile.direction = dir
Projectile.image_angle = dir
// Set projectile stats
Projectile.speed = 5
An architecutal decision exists whether collisions are mangaged by the projectile or the things it hits. We will have the projectile manage its own collisions.
For implementation, let's use the built-in GameMaker collision events. Right now, we will have the projectile destroy itself and the enemy upon a collision.
/// @description Destroy enemy and self
Syntax is simple, instance_destroy() has an optional parameter for an instance ID, and GameMaker populates the variable other with the other instance ID involved in the collision for collision events.
// Upon collision with an enemy, destroy enemy and self