我正在使用 SFML 来设计粒子系统。问题是游戏变慢了,而且我一直在变慢vector subscript out of range
。
这是我的代码:
#pragma once
#include<SFML\Graphics.hpp>
#include"stdafx.h"
struct particle
{
sf::Vector2<float> pos;
sf::Vector2<float> vel;
sf::Color color;
};
class pengine
{
private:
std::list<particle*> hitspark;
std::list<particle*>::iterator it;
int size;
sf::Image img;
sf::Texture text;
sf::Sprite sp;
public:
pengine();
void fuel(sf::Vector2f);
void update();
void render(sf::RenderWindow &name);
void cleanup();
};
pengine::pengine()
{
img.create(with,heit,sf::Color::Transparent);
hitspark.clear();
text.create(with,heit);
sp.setTexture(text);
}
void pengine::fuel(sf::Vector2f v1)
{
for(int i=0;i<10;i++)
{
particle* p;
p->color=sf::Color(rand()%255,rand()%255,rand()%255);
p->pos=v1;
float r1 = (float)rand()/((float)RAND_MAX/6.238);
float r2 = (float)rand()/((float)RAND_MAX/6.238);
p->vel.x=cos(r1);
p->vel.y=cos(r2);
if(p->vel.x!=0.0f&&p->vel.y!=0.0f)
{
hitspark.push_back(p);
delete p;
continue;
}
else {
delete p;
continue;}
}
}
void pengine::update()
{
for(it=hitspark.begin();it!=hitspark.end();it++)
{
(*it)->pos.x+=(*it)->vel.x;
(*it)->pos.y+=(*it)->vel.y;
(*it)->vel.x-=0.005;
(*it)->vel.y-=0.005;
}
cleanup();
}
void pengine::cleanup()
{
for(std::list<particle*>::iterator t=hitspark.begin();t!=hitspark.end();t++)
{
if((*t)->vel.x==0.0f && (*t)->vel.y==0.0f)
{
std::list<particle*>::iterator it=hitspark.end() ;
it--;
std::swap(*t,*it);
delete (*it);
hitspark.pop_back();
}
if((*t)->pos.x<=0||(*t)->pos.x>=with||(*t)->pos.y<=0||(*t)->pos.y>=heit)
{
std::list<particle*>::iterator it=hitspark.end() ;
it--;
std::swap(*t,*it);
delete (*it);
hitspark.pop_back();
}
}
}
void pengine::render(sf::RenderWindow &name)
{
for(std::list<particle*>::iterator s=hitspark.begin();s!=hitspark.end();s++)
{
img.setPixel((int)((*s)->pos.x),(int)((*s)->pos.y),(*s)->color);
}
const sf::Uint8*piarray=img.getPixelsPtr();
text.update(piarray);
name.draw(sp);
}