cocos2dx不响应透明区域事件

前端之家收集整理的这篇文章主要介绍了cocos2dx不响应透明区域事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在需要对某些图片的不规则点击区域响应事件

思路是遍历图片上的点.如果是透明区域就不响应事件

过程是在hitTest中做


可以写在基类中.如Node,我是写在Widget::Button中,并且没有完全完善,比如只做了buttonNormalRenderer的.大家可以根据思路用在其它地方.

//.h

	//按钮可支持多边形,透明区域不击中
public:
	void setSupportPolygonTouch(bool value){ _supportPolygon = value; }

   protected:
	   bool _supportPolygon;


//.cpp

	//add by jj
	bool Button::hitTest(const Vec2 &pt)
	{
		if (!_supportPolygon || _scale9Enabled)
			return Widget::hitTest(pt);
		Vec2 nsp = this->convertToNodeSpace(pt);
		Rect bb;
		bb.size = _contentSize;
		if (bb.containsPoint(nsp))
		{
			RenderTexture* render = RenderTexture::create(_buttonNormalRenderer->getContentSize().width,_buttonNormalRenderer->getContentSize().height,Texture2D::PixelFormat::RGBA8888);

			Sprite *sprite = static_cast<Sprite*>(_buttonNormalRenderer);
			Texture2D *texture = sprite->getTexture();
			Sprite *tmp = Sprite::createWithTexture(texture,sprite->getTextureRect());
			tmp->setVisible(true);
			tmp->setAnchorPoint(Vec2::ZERO);
			tmp->setPosition(Vec2::ZERO);
			render->beginWithClear(0,0);
			tmp->visit();
			//GLubyte pColor[4];
			//glReadPixels(nsp.x,nsp.y,1,GL_RGBA,GL_UNSIGNED_BYTE,&pColor[0]);
			render->end();
			Director::getInstance()->getRenderer()->render();
			Image *img = render->newImage(false);
			Color4B color = img->getColorAtPos(nsp.x,nsp.y);
			//render->saveToFile("test.png");
			if (color.a || color.b || color.g)
				return true;
		}
		return false;
	}

//关键位置CCImage.h


	Color4B <span style="font-family: Arial,Helvetica,sans-serif;">getColorAtPos</span><span style="font-family: Arial,sans-serif;">(float x,float y)</span>
	{
		Color4B color = { 0,0 };
		int ix = (int)x - 1;
		int iy = (int)y - 1;
		unsigned char *tmp = _data;
		tmp += (iy*getWidth() + ix) * 4;
		color.r = *(tmp++);
		color.g = *(tmp++);
		color.b = *(tmp++);
		color.a = *(tmp++);
		return color;
	};
之前有考虑用glReadPixels.不知道为什么读出来的都是0.求大神解答

猜你在找的Cocos2d-x相关文章