粒子系统(1)

一个基本的粒子系统的操作,包括粒子的初始化、粒子的更新以及粒子的消灭。

粒子的初始化:

1.申请vertex buffer

device->CreateVertexBuffer(
		_vbSize * sizeof(Particle) ,
		D3DUSAGE_DYNAMIC | D3DUSAGE_POINTS | D3DUSAGE_WRITEONLY ,
		Particle::FVF ,
		D3DPOOL_DEFAULT ,
		&_vb ,
		0);

2.设置粒子的纹理

D3DXCreateTextureFromFile(
		device,
		texFileName,
		&_tex);

3.初始化每一个粒子

	attribute->_isAlive = true;//粒子初始时为活
	attribute->_position = _origin;//粒子的初始位置

	D3DXVECTOR3 min = D3DXVECTOR3(-1.0f , -1.0f , -1.0f);
	D3DXVECTOR3 max = D3DXVECTOR3( 1.0f ,  1.0f ,  1.0f);

	GetRandomVector(&attribute->_velocity , &min , &max);

	D3DXVec3Normalize(&attribute->_velocity , &attribute->_velocity);

	attribute->_velocity *= 100.0f;//粒子的初始速度,矢量,可以决定粒子的当前位置

	attribute->_color = D3DXCOLOR(	//粒子的颜色
		GetRandomFloat(0.0f , 1.0f) ,
		GetRandomFloat(0.0f , 1.0f) ,
		GetRandomFloat(0.0f , 1.0f) ,
		1.0f);

	attribute->_age = 0.0f;//粒子的年龄
	attribute->_lifeTime = 2.0f;//粒子的寿命

当粒子初始化完成时,需要的时候就可以在屏幕上渲染了,渲染的时候,每一帧更新粒子的当前状态,比如速度、寿命、活性等:

	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)
				i->_isAlive = false;
		}
	}

这两天跑龙书上的代码,因为粗心浪费了很多的时间,泪目T T

你可能感兴趣的:(粒子系统(1))