我試圖端口Cocos2dx像素完美碰撞檢測的原始版本做了Cocos2D中,可以在這裏找到:http://www.cocos2d-iphone.org/forums/topic/pixel-perfect-collision-detection-using-color-blending/像素完美碰撞檢測中Cocos2dx
這裏是我的Cocos2dx碼版本
bool CollisionDetection::areTheSpritesColliding(cocos2d::CCSprite *spr1, cocos2d::CCSprite *spr2, bool pp, CCRenderTexture* _rt) { bool isColliding = false; CCRect intersection; CCRect r1 = spr1->boundingBox(); CCRect r2 = spr2->boundingBox(); intersection = CCRectMake(fmax(r1.getMinX(),r2.getMinX()), fmax(r1.getMinY(), r2.getMinY()) ,0,0); intersection.size.width = fmin(r1.getMaxX(), r2.getMaxX() - intersection.getMinX()); intersection.size.height = fmin(r1.getMaxY(), r2.getMaxY() - intersection.getMinY()); // Look for simple bounding box collision if ((intersection.size.width>0) && (intersection.size.height>0)) { // If we're not checking for pixel perfect collisions, return true if (!pp) { return true; } unsigned int x = intersection.origin.x; unsigned int y = intersection.origin.y; unsigned int w = intersection.size.width; unsigned int h = intersection.size.height; unsigned int numPixels = w * h; //CCLog("Intersection X and Y %d, %d", x, y); //CCLog("Number of pixels %d", numPixels); // Draw into the RenderTexture _rt->beginWithClear(0, 0, 0, 0); // Render both sprites: first one in RED and second one in GREEN glColorMask(1, 0, 0, 1); spr1->visit(); glColorMask(0, 1, 0, 1); spr2->visit(); glColorMask(1, 1, 1, 1); // Get color values of intersection area ccColor4B *buffer = (ccColor4B *)malloc(sizeof(ccColor4B) * numPixels); 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 0 && color.g > 0) { isColliding = true; break; } } // Free buffer memory free(buffer); } return isColliding; }
如果我將「pp」參數發送爲false,那麼我的代碼工作正常。這就是說,如果我只做一個邊界框碰撞,但當我需要Pixel Perfect碰撞時,我無法正確工作。 我認爲opengl掩碼不能按我的意圖工作。
這裏是「_rt」
_rt = CCRenderTexture::create(visibleSize.width, visibleSize.height); _rt->setPosition(ccp(origin.x + visibleSize.width * 0.5f, origin.y + visibleSize.height * 0.5f)); this->addChild(_rt, 1000000); _rt->setVisible(true); //For testing
我想我犯了一個錯誤與此CCRenderTexture實施
任何人都可以指導我什麼我做錯了的代碼?
感謝您的時間:)
我很抱歉。我做了一個錯誤的複製粘貼。我現在改變了上面的問題..但問題仍然存在 –