cocos2dx之setTouchesBegan

下面为创建球的例子,目的是为了去点击球体,让就能够获得press的消息,代码如下:

	for(int i = 0; i < kBallCount; ++i) {
		CCSprite *sprite_ball = CCSprite::create("MyBall.jpg");
		sprite_ball->setTag(i);
		sprite_ball->setPosition(ccp(size.width / 4, size.height / 4));
		ccBlendFunc bf = {GL_POINT_BIT, GL_ONE,}; //这里定义背景的颜色
		sprite_ball->setBlendFunc(bf);

		int iTime = rand() % 6;
		int iRandPosition = rand() % 7 + 1;
		CCMoveTo *move = CCMoveTo::create(iTime, CCPoint(size.width / iRandPosition, size.height /iRandPosition));
		sprite_ball->runAction(move);
		selected_ball->addObject(sprite_ball);
		addChild(sprite_ball, 1);
	}
	this->setTouchEnabled(true); //一定要设置为true,否则不会接到消息


 

在设置完了是否接受消息后,它相应ccTouchesBegan这个方法,代码如下:

void MyScene::ccTouchesBegan(CCSet *pTouches, CCEvent *pEvent) {
	CCTouch *touch = dynamic_cast<CCTouch *>(pTouches->anyObject());
	if(!touch) return ;
	CCSprite *sprite = 0;
	CCPoint point = touch->getLocation();

	int ballCount = 0;
	if(selected_ball) {
		ballCount = selected_ball->count();
	}

	for(int i = 0; i < ballCount; ++i) {
		CCSprite *spriteBall = dynamic_cast<CCSprite *>(selected_ball->objectAtIndex(i));
		int iBallPositionX = spriteBall->getPositionX();
		int iBallPositionY = spriteBall->getPositionY();

		int IBallWidth = spriteBall->getContentSize().width;
		int IBallHeight = spriteBall->getContentSize().height;

		CCRect rect =CCRect(
						iBallPositionX - spriteBall->getContentSize().width / 2,
						iBallPositionY - spriteBall->getContentSize().height / 2,
						IBallWidth,
						IBallHeight
			);
		if(rect.containsPoint(point)) {
			sprite = spriteBall;
			break;
		}
	}

	if(sprite) {
		this->removeChild(sprite,true); //先从layer中删掉
 		selected_ball->removeObject(sprite, true);//从数组队列中删掉
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值