Hello community!
I’m trying to do a pixel detection function, after failing with a pixel perfect collision detection with masks. I thought it would be easier to handle one point but im also stuck.
I am creating a RenderFrame, all black and placing a sprite on it. Then im trying to read the color of the point I’m touching, and if it’s not black, it means I’ve touched my sprite. Everything seems perfect but I am getting different color data, I mean, it’s not black nor mySprite’s color. I don’t really know what is happening but I am pretty sure that the buffer is loading information from somewhere else than the RenderFrame. Here goes the code:
bool CollisionDetection::isTheSpriteBeingTouched(Sprite* sprite1,
Touch* touch,
bool pp,
RenderTexture* rt)
{
auto size = Director::getInstance()->getWinSize();
rt->beginWithClear( 0, 0, 0, 0);
sprite1->visit();
auto position = touch->getLocation();
auto x = position.x * (CC_CONTENT_SCALE_FACTOR());
auto y = position.y * (CC_CONTENT_SCALE_FACTOR());
auto buffer = (Color4B *)malloc(sizeof(Color4B));
// Get color values of intersection area
glReadPixels(x, y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
rt->end();
// Read buffer
for(unsigned int i = 0; i < 1; i++) {
CCLOG("the color values: %d, %d, %d and the a: %d ",buffer->r,buffer->g,buffer->b, buffer->a);
// Here we check if a single pixel has both RED and BLUE pixels
if (buffer->r > 0 || buffer->g > 0 || buffer->b > 0) {
CCLOG("FOUND");
}else{
CCLOG("NOT FOUND");
}
}
free(buffer);
return false;
}
And here is how I declare my RenderTexture:
collisionDetectionRenderTexture_ =
RenderTexture::create(winSize.width, winSize.height, Texture2D::PixelFormat::RGBA4444);
collisionDetectionRenderTexture_->setVisible(true);
collisionDetectionRenderTexture_->ignoreAnchorPointForPosition(false);
this->addChild(collisionDetectionRenderTexture_, 5000);
collisionDetectionRenderTexture_->setPosition(Point(winSize.width * .5f, winSize.height * .5f));
Any help is highly appreciated!