我目前正在制作一个粒子系统,一个基本的,也使用 Allegro 5 库。
这是我想出的:
int main()
{
int mouseX = 0, mouseY = 0;
int randNum = 0;
std::vector <Particle *> Particles;
bool running = false, redraw = false, mouseHold = false;
int particleCount = 0;
al_init();
al_init_image_addon();
al_install_mouse();
al_init_font_addon();
al_init_ttf_addon();
ALLEGRO_DISPLAY* display = al_create_display(800, 600);
ALLEGRO_EVENT_QUEUE* event_queue = al_create_event_queue();
ALLEGRO_TIMER* myTimer = al_create_timer(1.0 / 60);
ALLEGRO_TIMER* pTimer = al_create_timer(1.0 / 120);
ALLEGRO_FONT* myFont = al_load_ttf_font("MyFont.ttf", 20, NULL);
al_register_event_source(event_queue, al_get_display_event_source(display));
al_register_event_source(event_queue, al_get_timer_event_source(myTimer));
al_register_event_source(event_queue, al_get_timer_event_source(pTimer));
al_register_event_source(event_queue, al_get_mouse_event_source());
running = true;
al_start_timer(myTimer);
while(running)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
running = false;
if(ev.type == ALLEGRO_EVENT_MOUSE_AXES)
{
mouseX = ev.mouse.x;
mouseY = ev.mouse.y;
}
if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
{
if(ev.mouse.button == 1)
mouseHold = true;
}
if(ev.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP)
{
if(ev.mouse.button == 1)
mouseHold = false;
}
if(ev.type == ALLEGRO_EVENT_TIMER)
{
randNum = (std::rand()+1 * ev.timer.count) % 50;
std::cout << randNum << std::endl;
if(mouseHold)
{
Particle* particle = new Particle(mouseX + randNum, mouseY + randNum);
Particles.push_back(particle);
}
particleCount = Particles.size();
for(auto i : Particles)
i->Update();
redraw = true;
}
for(auto iter = Particles.begin(); iter != Particles.end(); )
{
if(!(*iter)->GetAlive())
{
delete (*iter);
iter = Particles.erase(iter);
}
else
iter++;
}
if(redraw && al_event_queue_is_empty(event_queue))
{
for(auto i : Particles)
i->Draw();
al_draw_textf(myFont, al_map_rgb(0,200,0), 0, 10, NULL, "Mouse X: %i", mouseX);
al_draw_textf(myFont, al_map_rgb(0,200,0), 0, 30, NULL, "Mouse Y: %i", mouseY);
al_draw_textf(myFont, al_map_rgb(0,200,0), 0, 60, NULL, "Particle Count: %i", particleCount);
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
redraw = false;
}
}
al_destroy_display(display);
al_destroy_event_queue(event_queue);
al_destroy_timer(myTimer);
for(auto i : Particles)
delete i;
Particles.clear();
return 0;
}
是的,代码很糟糕。似乎我对 C++ 背后的理论了解比实际实现它更多。但我猜我正在学习。
问题:
有人说我不能多次调用“新”和“删除”,因为这非常糟糕。
粒子的创建受到计时器的限制——我不能/不知道如何制作它,所以我可以控制粒子创建的速度。
我不希望有人为我创造,如果我可以阅读一些东西来帮助我理解或有人发布一些代码来学习/让我思考,那将很有用?