因为在做项目的时候需要用到cocos2dx闪电效果,所以就照了相关的资料,把cocos2dx闪电效果做出来在这跟大家分享一下,
下面直接上代码,这其实就是一个算法问题:
.h文件
  1. [cpp]
  2. #ifndef __HELLO_LIGHTING_H__
  3. #define __HELLO_LIGHTING_H__
  4. #include "cocos2d.h"
  5. USING_NS_CC;
  6. class HelloLighting : public cocos2d::Layer
  7. {
  8. public:
  9. HelloLighting(void);
  10. ~HelloLighting(void);
  11. virtual bool init();
  12. virtual void update(float delta);
  13. static cocos2d::Scene* createScene();
  14. CREATE_FUNC(HelloLighting);
  15. virtual void draw(cocos2d::Renderer *renderer,const cocos2d::Mat4& transform,uint32_t flags);
  16. void drawLighting(float x1, float y1, float x2, float y2, float displace);
  17. private:
  18. float curDetail;
  19. Point pos1;
  20. Point pos2;
  21. };
  22. #endif //__HELLO_LIGHTING_H__
.cpp文件
  1. [cpp]
  2. #include "HelloLighting.h"
  3. HelloLighting::HelloLighting(void)
  4. {
  5. }
  6. HelloLighting::~HelloLighting(void)
  7. {
  8. }
  9. cocos2d::Scene* HelloLighting::createScene()
  10. {
  11. Scene *scene = Scene::create();
  12. HelloLighting *layer = HelloLighting::create();
  13. scene->addChild(layer);
  14. return scene;
  15. }
  16. bool HelloLighting::init()
  17. {
  18. if ( !CCLayer::init() )
  19. {
  20. return false;
  21. }
  22. auto winSize = Director::sharedDirector()->getWinSize();
  23. pos1 = Point(100, winSize.height/2);
  24. pos2 = Point(winSize.width-100, winSize.height/2);
  25. curDetail = 5;
  26. return true;
  27. }
  28. void HelloLighting::update( float delta )
  29. {
  30. }
  31. void HelloLighting::draw(cocos2d::Renderer *renderer,const cocos2d::Mat4& transform,uint32_t flags)
  32. {
  33. ccDrawColor4B(255, 0, 0, 0);
  34. glLineWidth(1);
  35. drawLighting(pos1.x, pos1.y, pos2.x, pos2.y, 200);  //这里多画几条线就可以看到更多了
  36. }
  37. void HelloLighting::drawLighting( float x1, float y1, float x2, float y2, float displace )
  38. {
  39. if (displace < curDetail)
  40. {
  41. ccDrawLine(ccp(x1,y1), ccp(x2,y2));
  42. }
  43. else
  44. {
  45. float mid_x = (x2+x1)/2;
  46. float mid_y = (y2+y1)/2;
  47. mid_x += (CCRANDOM_0_1() - 0.5) * displace;
  48. mid_y += (CCRANDOM_0_1() - 0.5) * displace;
  49. drawLighting(x1, y1, mid_x, mid_y, displace/2);
  50. drawLighting(x2, y2, mid_x, mid_y, displace/2);
  51. }
  52. }

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

cocos2dx闪电效果