烟火的粒子系统实现介绍

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DY_1024/article/details/87368800

之前的两篇博客介绍了粒子系统和粒子系统中的绘制:DirectX中的粒子系统粒子系统的绘制

其中介绍的也是粒子系统中比较通用的方法以及属性,但是具体的粒子系统还是需要根据自己的情况来添加一些新的方法,现在我们就来简单的看一下实现一个具体的烟火粒子系统(Firework)需要实现的具体的内容。

Firework实现还是需要继承于基础的PSysstem类的。

具体的PSystem的可以查看博客:DirectX中的粒子系统

class Firework:public PSystem 
{
	public: 
		Firework(D3DXVECTOR3* origin,int numparticles); 
		void resetParticle(Attribute* attribute); 
		void update(float timeDelta); 
		void preRender(); 
		void postRender();
};

该类里面的构造函数,有两个参数一个是粒子源的位置,也就是烟火爆炸的位置,还有有一个就是这个粒子系统中能容纳的最大的粒子数目。

resetParticle方法就是在粒子源中,对粒子进行初始化,并在球体中创建了一个随机向量。

Firework里面的粒子都被随机的赋予一种颜色,最后我们将粒子的生命周期定义为2秒。

void Firework:: resetParticle(Attribute* attribute)
{
	//粒子刚开始的初始状态置为true,
	attribute->isAlive =true; 
	//粒子的初始位置在爆炸源的位置
	attribute->_position=_origin; 

	//设置一下获取随机变量的范围
	D3DXVECTOR3 min=D3DXVECTOR3(-1.0f,-1.0f,-1.0f); 
	D3DXVECTOR3 max=D3DXVECTOR3(1.0f,1.0f,1.0f); 

	//获取一个随机向量 ,让烟火随机的发射
	//attribute->_velocity为输出的随机向量
	d3d:: GetRandomVector(
		&attribute->_velocity,
		& min,
		& max
		);
	
	//normalize to make spherical 
	//该函数返回一个规格化的向量
	D3DXVec3Normalize(
		&attribute->_velocity, 
		&attribute->_velocity
		); 
		
	//扩大100倍
	attribute->_velocity*=100.0f; 
	//获取一个随机颜色赋值
	attribute->color=D3DXCOLOR(
		d3d:: GetRandomFloat(0.0f,1.0f),
		d3d:: GetRandomFloat(0.0f,1.0f),
		d3d:: GetRandomFloat(0.0f,1.0f),
		1.0f
		); 

	attribute->_age = 0.0f; 
	attribute->_liferime=2.0f;//lives for 2 seconds
}

updata方法用来更新粒子的位置以及状态,updata本来应该做的是杀死超过范围或者声明周期的粒子,但是我们现在只是更新粒子的位置以及状态,这样就避免了频繁创建和销毁粒子的过程。

void Firework:: update(float timeDelta)
//传进来的参数是每一帧经过的时间
{
	//创建一个list迭代器
	std:: list<Attribute>:: iterator i; 
	//使用迭代器来遍历粒子系统里面的粒子
	for(i=_particles. begin();i!=_particles. end();i++)
	{
		//只更新活着的粒子
		if(i->isAlive)
		{
			//根据每一帧的时间乘以随机向量来更新粒子的位置
			i->_position+=i->_velocity* timeDelta;
			//每一帧的时间都算进粒子的存活时间
			i->_age += timeDelta; 
			//如果存活时间大于生命周期,则杀死
			if(i->_age>i->_lifeTime)//kil1
				i->isAlive = false;
		}
	}
}

重载preRender和postRender

void Firework::preRender()
{
	PSystem::preRender(); 
	_device->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_ONE);
	_device->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_ONE);
	// 	读取,但是不要将粒子写入z缓冲区
	device->SetRenderState(D3DRS_ZWRITEENABLE,false); 
}

void Firework::postRender()
{
	PSystem::postRender(); 
	_device->SetRenderState(D3DRS_ZWRITEENABLE,true);
}

上面的两个方法都使用了父类的方法,然后做了细微的改动。

猜你喜欢

转载自blog.csdn.net/DY_1024/article/details/87368800