基于像素的碰撞检测(移植到cocos2dx 3.x)

基于像素的碰撞检测(移植到cocos2dx 3.x),第1张

概述感谢原文:http://blog.muditjaju.infiniteeurekas.in/?p=1 我是从这里看到的:http://blog.csdn.net/xiebaochun/article/details/26455027 原文是cocos2dx 2.x的,我修改了一下,这个版本是Cocos2d-x 3.x可用版本。 Pixel Perfect Collision Detection ( 感谢原文:http://blog.muditjaju.infiniteeurekas.in/?p=1 我是从这里看到的:http://blog.csdn.net/xIEbaochun/article/details/26455027
原文是cocos2dx 2.x的,我修改了一下,这个版本是Cocos2d-x 3.x可用版本。
Pixel Perfect Collision Detection (Using Cocos2d-x 3.x)
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

////  CollisionDetection.h//  Created by Mudit Jaju on 30/08/13.////  SINGLetoN class for checking Pixel Based Collision Detection#ifndef __CollisionDetection__#define __CollisionDetection__#include <iostream>#include "cocos2d.h"class CollisionDetection {public:    //Handle for getting the Singleton Object    static CollisionDetection* GetInstance();    //Function signature for checking for collision detection spr1,spr2 are the concerned Sprites    //pp is bool,set to true if Pixel Perfection Collision is required. Else set to false    //_rt is the secondary buffer used in our system    bool areTheSpritesCollIDing(cocos2d::Sprite* spr1,cocos2d::Sprite* spr2,bool pp,cocos2d::RenderTexture* _rt);private:    static CollisionDetection* instance;    CollisionDetection();    // Values below are all required for openGL shading    cocos2d::GLProgram *glProgram;    cocos2d::color4B *buffer;    int uniformcolorRed;    int uniformcolorBlue;};#endif /* defined(__CollisionDetection__) */

CollisionDetection.cpp

////  CollisionDetection.cpp//  Created by Mudit Jaju on 30/08/13.////  SINGLetoN class for checking Pixel Based Collision Detection#include "CollisionDetection.h"USING_NS_CC;// Singleton Instance set to NulL initiallyCollisionDetection* CollisionDetection::instance = NulL;// Handle to get Singleton InstanceCollisionDetection* CollisionDetection::GetInstance() {    if (instance == NulL) {        instance = new CollisionDetection();    }    return instance;}// Private Constructor being called from within the GetInstance handleCollisionDetection::CollisionDetection() {    // Code below to setup shaders for use in Cocos2d-x    glProgram = new GLProgram();    glProgram->retain();    glProgram->initWithfilenames("SolIDVertexShader.vsh","SolIDcolorShader.fsh");    glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_name_position,GLProgram::VERTEX_ATTRIB_position);    glProgram->bindAttribLocation(GLProgram::ATTRIBUTE_name_TEX_COORD,GLProgram::VERTEX_ATTRIB_TEX_COORDS);    glProgram->link();    glProgram->updateUniforms();    glProgram->use();    uniformcolorRed = glGetUniformlocation(glProgram->getProgram(),"u_color_red");    uniformcolorBlue = glGetUniformlocation(glProgram->getProgram(),"u_color_blue");    // A large buffer created and re-used again and again to store glreadPixels data    buffer = (color4B *)malloc( sizeof(color4B) * 10000 );}bool CollisionDetection::areTheSpritesCollIDing(cocos2d::Sprite* spr1,RenderTexture* _rt) {    bool isCollIDing = false;    // Rectangle of the intersecting area if the Sprites are collIDing according to Bounding Box collision    Rect intersection;    // Bounding Box of the Two concerned Sprites being saved    Rect r1 = spr1->getBoundingBox();    Rect r2 = spr2->getBoundingBox();    // Look for simple bounding Box collision    if (r1.intersectsRect(r2)) {        // If we're not checking for pixel perfect collisions,return true        if (!pp) {            return true;        }        float tempX;        float tempY;        float tempWIDth;        float tempHeight;        //OPTIMIZE FURTHER        //CONSIDER THE CASE WHEN ONE BOUDNING Box IS COMPLETELY INSIDE ANOTHER BOUNDING Box!        if (r1.getMaxX() > r2.getMinX()) {            tempX = r2.getMinX();            tempWIDth = r1.getMaxX() - r2.getMinX();        } else {            tempX = r1.getMinX();            tempWIDth = r2.getMaxX() - r1.getMinX();        }        if (r2.getMaxY() < r1.getMaxY()) {            tempY = r1.getMinY();            tempHeight = r2.getMaxY() - r1.getMinY();        } else {            tempY = r2.getMinY();            tempHeight = r1.getMaxY() - r2.getMinY();        }        // We make the rectangle for the intersection area        intersection = Rect(tempX * CC_CONTENT_SCALE_FACTOR(),tempY * CC_CONTENT_SCALE_FACTOR(),tempWIDth * CC_CONTENT_SCALE_FACTOR(),tempHeight * CC_CONTENT_SCALE_FACTOR());        unsigned int x = intersection.origin.x;        unsigned int y = intersection.origin.y;        unsigned int w = intersection.size.wIDth;        unsigned int h = intersection.size.height;        // Total pixels whose values we will get using glreadPixels depends on the Height and WIDth of the intersection area        unsigned int numPixels = w * h;        // Setting the custom shader to be used        spr1->setGLProgram(glProgram);        spr2->setGLProgram(glProgram);        glProgram->use();        // Clearing the Secondary Draw buffer of all prevIoUs values        _rt->beginWithClear( 0,0);        // The below two values are being used in the custom shaders to set the value of RED and BLUE colors to be used        gluniform1i(uniformcolorRed,255);        gluniform1i(uniformcolorBlue,0);		BlendFunc blen_SRCAlpha_ONE={GL_SRC_Alpha,GL_ONE};		BlendFunc blen_BLEND_SRC_BLEND_DST={CC_BLEND_SRC,CC_BLEND_DST};		        // The blend function is important we don't want the pixel value of the RED color being over-written by the BLUE color.       // 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)				spr1->setBlendFunc(blen_SRCAlpha_ONE);        // The visit() function draws the sprite in the _rt draw buffer its a Cocos2d-x function        spr1->visit();        // Setting the shader program back to the default shader being used by our game        		spr1->setGLProgram(shadercache::getInstance()->getGLProgram(GLProgram::SHADER_name_position_TEXTURE_color_NO_MVP));        // Setting the default blender function being used by the game        spr1->setBlendFunc(blen_BLEND_SRC_BLEND_DST);		        // Setting new values for the same shader but for our second sprite as this time we want to have an all BLUE sprite		        gluniform1i(uniformcolorRed,0);        gluniform1i(uniformcolorBlue,255);        spr2->setBlendFunc(blen_SRCAlpha_ONE);        spr2->visit();        spr2->setGLProgram(CCshadercache::getInstance()->getGLProgram(GLProgram::SHADER_name_position_TEXTURE_color_NO_MVP));        spr2->setBlendFunc(blen_BLEND_SRC_BLEND_DST);		        // Get color values of intersection area        glreadPixels(x,y,w,h,GL_RGBA,GL_UNSIGNED_BYTE,buffer);		        _rt->end();        // Read buffer        unsigned int step = 1;        for(unsigned int i=0; i<numPixels; i+=step) {            color4B color = buffer[i];            // Here we check if a single pixel has both RED and BLUE pixels            if (color.r > 0 && color.b > 0) {                isCollIDing = true;                break;            }        }    }    return isCollIDing;}

SolIDcolorShader.fsh

#ifdef GL_ESprecision lowp float;#endifvarying vec2 v_texCoord;uniform sampler2D u_texture;uniform int u_color_red;uniform int u_color_blue;voID main(){	vec4 color = texture2D(u_texture,v_texCoord);    gl_Fragcolor = vec4(u_color_red,u_color_blue,color.a);}

SolIDVertexShader.vsh

attribute vec4 a_position;							attribute vec2 a_texCoord;							attribute vec4 a_color;								#ifdef GL_ES										varying lowp vec4 v_fragmentcolor;					varying mediump vec2 v_texCoord;					#else												varying vec4 v_fragmentcolor;						varying vec2 v_texCoord;							#endif												voID main()											{													    gl_position = CC_MVPMatrix * a_position;			v_fragmentcolor = a_color;							v_texCoord = a_texCoord;						}

For using the Collision Detection Class:

1. Initialize the CCRenderTexture object

    _rt = RenderTexture::create(visibleSize.wIDth * 2,visibleSize.height * 2);    _rt->setposition(ccp(visibleSize.wIDth,visibleSize.height));    _rt->retain();    _rt->setVisible(false);

2. Call the Singleton function whenever collision detection required

if (CollisionDetection::GetInstance()->areTheSpritesCollIDing(pSprite,pCurrentSpritetoDrag,true,_rt)) {     //Code here}
总结

以上是内存溢出为你收集整理的基于像素碰撞检测(移植到cocos2dx 3.x)全部内容,希望文章能够帮你解决基于像素的碰撞检测(移植到cocos2dx 3.x)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1027542.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存