CrociDB Tutorials

Particles with Allegro

Like two years ago, I made a test of Particles with C and Allegro. You might ask me why not C++. I used C because I was making a tutorial of particles in C, and I think it's good to start with.

It's really simple, and the code is not commented (i'm sorry), but it's easy to understand and may help you.

Here is a video of the code working:



And here is the simple code. Good luck trying to read that. =D


#define MAX_PARTICLES           2000

#include <allegro.h>
#include <stdio.h>
#include <time.h>

void init();

typedef struct tParticle
{
    float x, y;
    float x1, y1;
    float vel, velx;
    BITMAP *bmp;
};

tParticle part[MAX_PARTICLES];

void part_install();
void part_init(int index);
void part_render(BITMAP *dbuffer);
void part_update();

int main()
{
    init();
    BITMAP *buffer = create_bitmap(640, 480);

    part_install();

    while(!key[KEY_ESC])
    {
        clear(buffer);

        part_render(buffer);
        part_update();

        blit(buffer, screen, 0, 0, 0, 0, 640, 480);
    }

    readkey();            // wait for a key to be pressed

    return 0;
}
END_OF_MAIN()

void init()
{
    allegro_init();
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, 640, 480, 0, 0);

    install_keyboard();   // when you use the inputter, you also have to
    install_mouse();

    srand(time(NULL));
}

void part_install()
{
    int c;
    for (int i = 0; i < MAX_PARTICLES; i++)
    {
        part[i].x = mouse_x;
        part[i].y = mouse_y;
        part[i].x1 = mouse_x;
        part[i].y1 = mouse_y;
        part[i].bmp = create_bitmap(1, 1);
        c = (rand()%255);
        clear_to_color(part[i].bmp, makecol(c-50, c-50, c));
        part[i].vel = (rand() % 3)+1;
        part[i].velx = (rand()%5+0.25) * ((rand()%2 == 1?-1:1));
    }
}

void part_init(int index)
{
    part[index].x = mouse_x;
    part[index].y = mouse_y;
    part[index].x1 = mouse_x;
    part[index].y1 = mouse_y;
    part[index].vel = (rand() % 3)+1;

    //clear_to_color(part[index].bmp, makecol((rand()%255), (rand()%255), (rand()%255)));
}

void part_render(BITMAP *dbuffer)
{
    for (int i = 0; i < MAX_PARTICLES; i++)
    {
        draw_sprite(dbuffer, part[i].bmp, part[i].x, part[i].y);
    }
}

void part_update()
{
    for (int i = 0; i < MAX_PARTICLES; i++)
    {
        part[i].y += part[i].vel;
        part[i].x += part[i].velx;
        part[i].velx = (rand()%5+0.25) * ((rand()%2 == 1?-1:1));
        part[i].vel = (rand() % 8)+3;

        if (part[i].y - part[i].y1 > (rand()%100)+100)
        {
            part_init(i);
        }
    }
}

As I said, the code isn't commented, but I intend to make a tutorial explaining all of the parts of this code.

Thanks.