Most games will have an enemy that exhibits some basic AI (Artificial Intelligence). This chapter serves as an introduction to some basic AI.
Avoid the player
Guard an area and attack the player if they get too close
Calculate the best play in a card game
Shoot a projectile at the player
Shoot at a player if they see them
Generally, you will evaluate some code and determine if it is true or false (or some other value) and make something happen as a result.
This section will start with a basic system and will add more features in stages.
Make three very basic sprites (32x32 in size) spr_wall, spr_player and spr_enemy, set the origin as center, then assign them to obj_wall, obj_player, and obj_enemy.
The preceding code will provide basic movement and prevent the player moving through a wall object.
Basically the code uses a key press and that there is not a wall in the way, if there is not, then it’s position is changed. sign(value) returns -1 for a negative value and 1 for a positive value. It is not perfect, but it will suffice for testing.
An example usage of sign()would be for setting the image_xscale of an instance so it points to the correct direction when moving left or right.
Check the movement works by testing.
Basic Enemy AI
This code will set an initial flag. We’ll use and change this when the enemy can or can’t see the player.
This will draw its own sprite, and a line between itself and player if can_see is true.
Load snd_ouch from the resources.
The preceding code will play the sound snd_ouch upon collision with the obj_player, and then destroy itself.
Enemy Shooting
Assign this sprite an object obj_bullet.
plays a sound and destroys itself upon collision with obj_player
sets an additional flag for shooting control
Set flag so it can shoot again.
Now test the game, if an enemy has a line of sight to the player, it will shoot a bullet every three seconds.
Basic Projects
- A)
Set an instance that moves randomly left and right across the top of the window (wrapping as needed). Set it to drop a collectible object every five seconds. Player to collect these items. Draw a basic HUD on screen.
- B)
Set up a player that can be moved with arrow keys. Set an enemy to shoot projectiles at the player, getting more frequent as the player gets closer. Destroy projectile when outside room.
Advanced Projects
- C)
Set an enemy that changes direction every five seconds away from the player.
Useful Functions
collision_rectangle(); Allows you to get a list of all instances in a gen area
collision_line_list(); Returns all instances that collide with a line
point_in_circle(); Return instances within a circular region
point_in_rectangle(); Return true or false, depending on whether a given coordinate falls in an area
point_in_triangle(); Returns instances within a triangular region
Summary
You now know some basic functions to make enemies react to player input and positions. You can gradually build upon this to create more complex enemy interactions.