Skip to main content

Command Palette

Search for a command to run...

Enemies shoot back!

Published
2 min read

For our enemies to be able to shoot back, they need to have a gun and bullet object dedicated to themselves. but first, we need to add a variable to our enemies to see if we have to spawn them with gun or without it so we add a “has_weapon” bool variable to it and we can change this at an instance level in the rooms.

Then, in our Create Event inside Enemy Object, we need to actually spawn the gun object if this variable is set to true . For this, we keep track of the gun in the enemy object and the enemy in the gun object.

if (has_weapon){
    my_gun = instance_create_layer(x, y, "gun", o_enemy_gun);
    with (my_gun){
        owner = other.id;
    }
} else {

    my_gun = noone;
}

O_Enemy_Gun

Create Event

Here we set a rate which the enemy shoots bullets.

countdown_rate = 200;
countdown = countdown_rate;

Begin Step Event

Here, we bind the gun to the enemy object (in case the enemy moves) and if the player exists and is in the range of enemy, we point the gun at the player. If the time limit has passed, we can actually shoot and spawn a bullet from enemy. The code is self explanatory.

x = owner.x;
y = owner.y;
image_xscale = 0.5;
image_yscale = 0.5;

if (instance_exists(o_player)){
    if (o_player.x < x){
        image_yscale = -image_yscale;
    }
    if (point_distance(o_player.x, o_player.y, x, y) < 150){
        image_angle = point_direction(x, y, o_player.x, o_player.y);
        countdown--;
        if (countdown <= 0){
            countdown = countdown_rate;
            if(!collision_line(x, y, o_player.x, o_player.y, tile_id, false, false)){
                audio_sound_pitch(sound_shoot, choose(0.8, 1, 1.2));
                audio_play_sound(sound_shoot, 5, false);
                with (instance_create_layer(x, y, "bullet", o_enemy_bullet)) {
                    speed = 1;
                    direction = other.image_angle + random_range(-3, 3);
                    image_angle = direction;
                }
            }
        }
    }
}

O_Enemy_Bullet

The code is pretty much the same as O_bullet so I wont explain it.

Pre-Draw Event


if (place_meeting(x, y, tile_id)) {
    while(place_meeting(x, y, tile_id)){
        x -= lengthdir_x(1, direction);
        y -= lengthdir_y(1, direction);
    }
    instance_change(o_hit_spark, true);
}

Animation End Event

image_speed = 0;
image_index = 1;

Of course if the bullet hits the player, the player should be dead and the bullet should be destroyed. We have the code snippet to do this like this:

function kill_player(){
    with(o_gun){
    instance_destroy();
    }

    instance_change(o_dead_player, true);
    direction = point_direction(other.x, other.y, x, y);

    _hor = lengthdir_x(4, direction);
    _ver = lengthdir_y(4, direction) - 2;



    if (sign(_hor) != 0) image_xscale = sign(_hor);
    global.kills -= global.killsThisRoom;
}