cocos2dx-3.2 之 闪电效果


参考闪电特效算法:http://krazydad.com/bestiary/bestiary_lightning.html

算法详细信息可参上述网址


下面直接上代码,这其实就是一个算法问题:

.h文件

#ifndef __HELLO_LIGHTING_H__
#define __HELLO_LIGHTING_H__

#include "cocos2d.h"
USING_NS_CC;

class HelloLighting : public cocos2d::Layer
{
public:
	HelloLighting(void);
	~HelloLighting(void);

	virtual bool init();
	virtual void update(float delta);
	static cocos2d::Scene* createScene();

	CREATE_FUNC(HelloLighting);

	virtual void draw(cocos2d::Renderer *renderer,const cocos2d::Mat4& transform,uint32_t flags);

	void drawLighting(float x1, float y1, float x2, float y2, float displace);

private:
	float curDetail;
	Point pos1;
	Point pos2;
};

#endif //__HELLO_LIGHTING_H__

.cpp文件

#include "HelloLighting.h"

HelloLighting::HelloLighting(void)
{
	
}


HelloLighting::~HelloLighting(void)
{
}

cocos2d::Scene* HelloLighting::createScene()
{
	Scene *scene = Scene::create();
	HelloLighting *layer = HelloLighting::create();
	scene->addChild(layer);
	return scene;
}

bool HelloLighting::init()
{
	if ( !CCLayer::init() )
	{
		return false;
	}
	auto winSize = Director::sharedDirector()->getWinSize();

	pos1 = Point(100, winSize.height/2);
	pos2 = Point(winSize.width-100, winSize.height/2);
	curDetail = 5;

	return true;
}

void HelloLighting::update( float delta )
{

}



void HelloLighting::draw(cocos2d::Renderer *renderer,const cocos2d::Mat4& transform,uint32_t flags)
{
	ccDrawColor4B(255, 0, 0, 0);
	glLineWidth(1);
	drawLighting(pos1.x, pos1.y, pos2.x, pos2.y, 200);  //这里多画几条线就可以看到更多了
}

void HelloLighting::drawLighting( float x1, float y1, float x2, float y2, float displace )
{
	if (displace < curDetail)
	{
		ccDrawLine(ccp(x1,y1), ccp(x2,y2));
	}
	else
	{
		float mid_x = (x2+x1)/2;
		float mid_y = (y2+y1)/2;
		mid_x += (CCRANDOM_0_1() - 0.5) * displace;
		mid_y += (CCRANDOM_0_1() - 0.5) * displace;
		drawLighting(x1, y1, mid_x, mid_y, displace/2);
		drawLighting(x2, y2, mid_x, mid_y, displace/2);
	}
}


直接加载这个场景就可以看到效果了,其实效果图跟运行效果还是有差别的,先来欣赏一下吧!

cocos2dx-3.2 之 闪电效果_第1张图片


你可能感兴趣的:(cocos2d-x,3.x)