(转)像素完美碰撞检测(使用cocos2d-x)

Pixel Perfect Collision Detection (Using Cocos2d-x)

Pixel perfect collision detection
 
This post found its way because I couldnt find the answer to one of the questions I asked on StackOverflow (http://stackoverflow.com/questions/18546066/pixel-perfect-collision-detection-in-cocos2dx) and thought there would be others like me in search for an answer.

Collision detection is an integral part of almost all games. It is used to find when a bullet hits an enemy or when you bump into a wall etc.
There are many different requirements when we do collision detection and depending on our game we choose one of the many detection techniques.

The default Collision detection mechanism used by games and provided in almost all game engines and frameworks is a “Bounding Box” collision.
Simply put, a “Bounding Box” collision detection system the sprites/objects being checked for collision are treated as the smallest rectangle which completely engulfs them. Then these two Boxes are checked if they are colliding with each other.

But sometimes this very simple collision detection system is not accurate. Specially when we use sprites with alpha values (mostly png files) or when our objects are rotated by some angles. See the image below:
 
 
Pixel – Perfect collision detection is a system where we check if the objects concerned are actually colliding rather than just being part of a bounding box which is bigger than their size. WARNING: This system though more accurate is obviously more performance intensive and hence depending on your game requirements choose wisely about which of the different systems you want to use.

TIP: This system though written specially for Cocos2d-x framework can be easily understood and implemented for any language/framework you are using.

So its time to get our hands dirty,

We are going to develop a Singleton Class for collision detection and just plug and play this in any project we are doing.

Things used:
1. Singleton Class – CollisionDetection
2. Opengl Vertex and Fragment Shaders
3. CCRenderTexture Class – Cocos2d-x

Theory:
1. Create a CCRenderTexture which is going to serve as a secondary draw buffer.
2. We first do a simple collision detection (Bounding Box) to check if the two sprite’s bounds are colliding
3. If step 2 is a success then we are going to draw the two concerned objects in our secondary buffer we created in step 1. (We are going to set its visibility to false, so that even though we draw something, nothing will we visible to the end user)
4. Using openGL fragment shaders we are going to draw one of the objects completely RED and the other completely BLUE!
 
 
5. Using another of openGL functionality glReadPixels we are going to read the pixels data of all the pixels in the Rectangular area (Intersection area) of the bounding box collision
6. We are then going to loop through all the pixel values and check if a single pixel has BOTH the RED and the BLUE pixels. If they have then the objects are actually colliding or else not.

Now here is the code for the above steps. I have commented the code for you to understand what is going on. If there are any questions please leave in the comments and I will try and answer to the best of my knowledge
 
CollisionDetection.h
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. //  
  2. //  CollisionDetection.h  
  3. //  Created by Mudit Jaju on 30/08/13.  
  4. //  
  5. //  SINGLETON class for checking Pixel Based Collision Detection  
  6.   
  7. #ifndef __CollisionDetection__  
  8. #define __CollisionDetection__  
  9.   
  10. #include <iostream>  
  11. #include "cocos2d.h"  
  12.   
  13. USING_NS_CC;  
  14.   
  15. class CollisionDetection {  
  16. public:  
  17.     //Handle for getting the Singleton Object  
  18.     static CollisionDetection* GetInstance();  
  19.     //Function signature for checking for collision detection spr1, spr2 are the concerned sprites  
  20.     //pp is bool, set to true if Pixel Perfection Collision is required. Else set to false  
  21.     //_rt is the secondary buffer used in our system  
  22.     bool areTheSpritesColliding(CCSprite* spr1, CCSprite* spr2, bool pp, CCRenderTexture* _rt);  
  23. private:  
  24.     static CollisionDetection* instance;  
  25.     CollisionDetection();  
  26.   
  27.     // Values below are all required for openGL shading  
  28.     CCGLProgram *glProgram;  
  29.     ccColor4B *buffer;  
  30.     int uniformColorRed;  
  31.     int uniformColorBlue;  
  32.   
  33. };  
  34.   
  35. #endif /* defined(__CollisionDetection__) */  

CollisionDetection.cpp
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. //  
  2. //  CollisionDetection.cpp  
  3. //  Created by Mudit Jaju on 30/08/13.  
  4. //  
  5. //  SINGLETON class for checking Pixel Based Collision Detection  
  6.   
  7. #include "CollisionDetection.h"  
  8. // Singleton Instance set to NULL initially  
  9. CollisionDetection* CollisionDetection::instance = NULL;  
  10.   
  11. // Handle to get Singleton Instance  
  12. CollisionDetection* CollisionDetection::GetInstance() {  
  13.     if (instance == NULL) {  
  14.         instance = new CollisionDetection();  
  15.     }  
  16.     return instance;  
  17. }  
  18.   
  19. // Private Constructor being called from within the GetInstance handle  
  20. CollisionDetection::CollisionDetection() {  
  21.     // Code below to setup shaders for use in Cocos2d-x  
  22.     glProgram = new CCGLProgram();  
  23.     glProgram->retain();  
  24.     glProgram->initWithVertexShaderFilename("SolidVertexShader.vsh", "SolidColorShader.fsh");  
  25.     glProgram->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);  
  26.     glProgram->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);  
  27.     glProgram->link();  
  28.     glProgram->updateUniforms();  
  29.     glProgram->use();  
  30.   
  31.     uniformColorRed = glGetUniformLocation(glProgram->getProgram(), "u_color_red");  
  32.     uniformColorBlue = glGetUniformLocation(glProgram->getProgram(), "u_color_blue");  
  33.   
  34.     // A large buffer created and re-used again and again to store glReadPixels data  
  35.     buffer = (ccColor4B *)malloc( sizeof(ccColor4B) * 10000 );  
  36. }  
  37.   
  38. bool CollisionDetection::areTheSpritesColliding(cocos2d::CCSprite* spr1, cocos2d::CCSprite* spr2, bool pp, CCRenderTexture* _rt) {  
  39.     bool isColliding = false;  
  40.   
  41.     // Rectangle of the intersecting area if the sprites are colliding according to Bounding Box collision  
  42.     CCRect intersection;  
  43.   
  44.     // Bounding box of the Two concerned sprites being saved  
  45.     CCRect r1 = spr1->boundingBox();  
  46.     CCRect r2 = spr2->boundingBox();  
  47.   
  48.     // Look for simple bounding box collision  
  49.     if (r1.intersectsRect(r2)) {  
  50.         // If we're not checking for pixel perfect collisions, return true  
  51.         if (!pp) {  
  52.             return true;  
  53.         }  
  54.   
  55.         float tempX;  
  56.         float tempY;  
  57.         float tempWidth;  
  58.         float tempHeight;  
  59.   
  60.         //OPTIMIZE FURTHER  
  61.         //CONSIDER THE CASE WHEN ONE BOUDNING BOX IS COMPLETELY INSIDE ANOTHER BOUNDING BOX!  
  62.         if (r1.getMaxX() > r2.getMinX()) {  
  63.             tempX = r2.getMinX();  
  64.             tempWidth = r1.getMaxX() - r2.getMinX();  
  65.         } else {  
  66.             tempX = r1.getMinX();  
  67.             tempWidth = r2.getMaxX() - r1.getMinX();  
  68.         }  
  69.   
  70.         if (r2.getMaxY() r1.getMaxY()) {  
  71.             tempY = r1.getMinY();  
  72.             tempHeight = r2.getMaxY() - r1.getMinY();  
  73.         } else {  
  74.             tempY = r2.getMinY();  
  75.             tempHeight = r1.getMaxY() - r2.getMinY();  
  76.         }  
  77.   
  78.         // We make the rectangle for the intersection area  
  79.         intersection = CCRectMake(tempX * CC_CONTENT_SCALE_FACTOR(), tempY * CC_CONTENT_SCALE_FACTOR(), tempWidth * CC_CONTENT_SCALE_FACTOR(), tempHeight * CC_CONTENT_SCALE_FACTOR());  
  80.   
  81.         unsigned int x = intersection.origin.x;  
  82.         unsigned int y = intersection.origin.y;  
  83.         unsigned int w = intersection.size.width;  
  84.         unsigned int h = intersection.size.height;  
  85.   
  86.         // Total pixels whose values we will get using glReadPixels depends on the Height and Width of the intersection area  
  87.         unsigned int numPixels = w * h;  
  88.   
  89.         // Setting the custom shader to be used  
  90.         spr1->setShaderProgram(glProgram);  
  91.         spr2->setShaderProgram(glProgram);  
  92.         glProgram->use();  
  93.   
  94.         // Clearing the Secondary Draw buffer of all previous values  
  95.         _rt->beginWithClear( 0, 0, 0, 0);  
  96.   
  97.         // The below two values are being used in the custom shaders to set the value of RED and BLUE colors to be used  
  98.         glUniform1i(uniformColorRed, 255);  
  99.         glUniform1i(uniformColorBlue, 0);  
  100.   
  101.         // The blend function is important we don't want the pixel value of the RED color being over-written by the BLUE color.  
  102.        // We want both the colors at a single pixel and hence get a PINK color (so that we have both the RED and BLUE pixels)  
  103.         spr1->setBlendFunc((ccBlendFunc){GL_SRC_ALPHA, GL_ONE});  
  104.   
  105.         // The visit() function draws the sprite in the _rt draw buffer its a Cocos2d-x function  
  106.         spr1->visit();  
  107.   
  108.         // Setting the shader program back to the default shader being used by our game          
  109. spr1->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));  
  110.         // Setting the default blender function being used by the game  
  111.         spr1->setBlendFunc((ccBlendFunc){CC_BLEND_SRC, CC_BLEND_DST});  
  112.   
  113.         // Setting new values for the same shader but for our second sprite as this time we want to have an all BLUE sprite  
  114.         glUniform1i(uniformColorRed, 0);  
  115.         glUniform1i(uniformColorBlue, 255);  
  116.         spr2->setBlendFunc((ccBlendFunc){GL_SRC_ALPHA, GL_ONE});  
  117.   
  118.         spr2->visit();  
  119.   
  120.         spr2->setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor));  
  121.         spr2->setBlendFunc((ccBlendFunc){CC_BLEND_SRC, CC_BLEND_DST});  
  122.   
  123.         // Get color values of intersection area  
  124.         glReadPixels(x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE, buffer);  
  125.   
  126.         _rt->end();  
  127.   
  128.         // Read buffer  
  129.         unsigned int step = 1;  
  130.         for(unsigned int i=0; i<numPixels; i+=step) {  
  131.             ccColor4B color = buffer[i];  
  132.             // Here we check if a single pixel has both RED and BLUE pixels  
  133.             if (color.r > 0 && color.b > 0) {  
  134.                 isColliding = true;  
  135.                 break;  
  136.             }  
  137.         }  
  138.     }  
  139.     return isColliding;  
  140. }  

 SolidColorShader.fsh
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #ifdef GL_ES  
  2. precision lowp float;  
  3. #endif  
  4.   
  5. varying vec2 v_texCoord;  
  6. uniform sampler2D u_texture;  
  7. uniform int u_color_red;  
  8. uniform int u_color_blue;  
  9.   
  10. void main()  
  11. {  
  12.     vec4 color = texture2D(u_texture, v_texCoord);  
  13.     gl_FragColor = vec4(u_color_red, 0, u_color_blue, color.a);  
  14.   
  15. }  

 SolidVertexShader.vsh
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. attribute vec4 a_position;                            
  2. attribute vec2 a_texCoord;                            
  3. attribute vec4 a_color;                               
  4.   
  5. #ifdef GL_ES                                          
  6. varying lowp vec4 v_fragmentColor;                    
  7. varying mediump vec2 v_texCoord;                      
  8. #else                                                 
  9. varying vec4 v_fragmentColor;                         
  10. varying vec2 v_texCoord;                              
  11. #endif                                                
  12.   
  13. void main()                                           
  14. {                                                     
  15.     gl_Position = CC_MVPMatrix * a_position;          
  16.     v_fragmentColor = a_color;                        
  17.     v_texCoord = a_texCoord;                          
  18. }  

For using the Collision Detection Class:

1. Initialize the CCRenderTexture object
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. _rt = CCRenderTexture::create(visibleSize.width * 2, visibleSize.height * 2);  
  2. _rt->setPosition(ccp(visibleSize.width, visibleSize.height));  
  3. _rt->retain();  
  4. _rt->setVisible(false);  

2. Call the Singleton function whenever collision detection required
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. if (CollisionDetection::GetInstance()->areTheSpritesColliding(pSprite, pCurrentSpriteToDrag, true, _rt)) {  
  2.      //Code here  
  3. }  
 
 
原文出处:http://blog.muditjaju.infiniteeurekas.in/?p=1
posted @ 2015-06-17 11:53  Mareon  阅读(458)  评论(0编辑  收藏  举报