下面为创建球的例子,目的是为了去点击球体,让就能够获得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);//从数组队列中删掉
	}
}