2013-10-26 21 views
0

我正在使用SFML來設計一個粒子系統。問題是遊戲變得緩慢,而且我繼續得到vector subscript out of rangeSFML - 粒子系統矢量超出範圍

這裏是我的代碼:

#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); 

} 

回答

1
particle* p; 

應該

particle* p = new particle(); 

另一個提示將

typedef std::list<particle*> Particles; 

所以你可以去粒子::迭代器。有點乾淨。

最後我想說,你做的事情都是錯的。如果你懶惰的話,粒子系統應該有恆定的大小,可能有一個數組或一個std :: vector。不是帶有指針的鏈表。

所以無論

std::vector<particle> 

template<int MAX_PARTICLES> 
class ParticleSystem 
{ Particle particles[MAX_PARTICLES]; }; 

我希望你的想法,這是非常非常快,而不高速緩存未命中。我更喜歡後者,但可能只是我。