• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

How to make enemy(walking,attack)

G

Gorshalox

Guest
I'm making ma first game(2d platformer) in GMS language,i don't know how to make enemy to walk to player and attack him,pls help me
 
Here's a basic FSM (Finite State Machine) that will help you divide the enemy logic in different states:

GML:
/// CREATE EVENT ============================
enemyState = "idle";  // You could also use an enumerator system
sightRange = 128;     // The radius of the sight area
enemySpeed = 4;       // The speed of the enemy
attackRange = 8;      // The distance in pixels where the enemy starts to attack when in the chase state

/// STEP EVENT ===========================
switch (enemyState) {
    case "idle":
        // Make sure the player's instance exists
        if (instance_exists(oPlayer)) {
            // Is the player in sight (?)
            var playerInSight = point_in_circle(oPlayer.x, oPlayer.y, x, y, sightRange);
            // The player is in the enemy sight range
            if (playerInSight) {
                // Chase the player
                enemyState = "chase";
            }
        }
    break;

    case "chase":
        // Make sure the player's instance exists
        if (instance_exists(oPlayer)) {
            // The player is in the attack range
            if (point_distance(x, y, oPlayer.x, oPlayer.y) < attackRange) {
                // Stop moving
                speed = 0;
                // Attack the player
                enemyState = "attack";
            } else {
                // Is the player in sight (?)
                var playerInSight = point_in_circle(oPlayer.x, oPlayer.y, x, y, sightRange);
                // The player is in the enemy sight range
                if (playerInSight) {
                    // Move towards the player
                    move_towards_point(oPlayer.x, oPlayer.y, enemySpeed);
                } else {
                    // The player is not in the sight range, go back to the idle state
                    enemyState = "idle";
                    speed = 0;
                }
            
            }
        }
    break;

    case "attack":
        // Attack the player
    break;

}
 
Last edited:
Top