Skip to main content

Command Palette

Search for a command to run...

Animations and Room Shakes

Published
•2 min read•View as Markdown

We can add some kind of shake animation to the camera when we shoot a enemy or break an item. To do this, we need to add some variables to our camera’s Create Object.

Create Event

//initialize shake values
shake_duration = 0;
shake_magnitude = 0;
shake_ramaining = 0;
buff = 32;

The duration of shake can be set in terms of frames. a 60 frame shake duration is 1 second of shaking. The magnitude shows how strong the shake is and the remaining shake option, gives us the ability to control and finish the shake animation. The buffer is used here to not let the camera pass room borders.

Step Event

Now, inside our Step Event we need to simply update our camera position randomly each frame as long as we have time left. We decrease the remaining shake in each frame by 1/

//clamp it so it dont go out of the room borders
x = clamp(x, view_w_half +buff, room_width - view_w_half - buff);
y = clamp(y, view_h_half +buff, room_height - view_h_half - buff);

//Screen shake
x += random_range(-shake_ramaining, shake_ramaining);
y += random_range(-shake_ramaining, shake_ramaining);
shake_ramaining = max(0, shake_ramaining - ((1/shake_duration)*shake_magnitude));

Also, as we see in the code above, we need to change our clamp functionality (which was for not exceeding room borders) with buffer so when we shake the screen on the borders, we don’t exceed either.

Script

Now that we have the code for our camera, we need to actually update some values outside of this code. We use a script for this purpose.

///@desc shakes the screen
///@arg magnitude sets the strength
///@arg frames sets the duration of shake 60 = 1s

function screen_shake(){
    with(o_camera){
        if (argument0 > shake_ramaining){
            shake_magnitude = argument0;
            shake_ramaining = argument0;
            shake_duration = argument1;
        }
    }
}

Usage

we can simply use this however we want. This is how it looks inside my shooting event.

if (mouse_check_button(mb_left) && firing_delay < 0){
    recoil = 4;
    firing_delay = 5;
    screen_shake(2, 10); //Here I call the screanshake before crearing the bullet to shoot
    with (instance_create_layer(x, y, "bullet", o_bullet)) {
        speed = 25;
        direction = other.image_angle + random_range(-3, 3);
        image_angle = direction;
    }
}

More from this blog

G

GameMaker Journey

14 posts

Here, I will share the code snippets about different basic functionalities in GameMaker