相信大家玩游戏的时候都有这个感觉吧,比如说植物大战僵尸中,我们要选中植物,然后去移动,选中植物后,植物的状态会发生改变,我们如果点击了其他的地方,没有将植物放到坑中,则植物的状态又会到原始的状态,今天就来实现一下这个效果,其实大家可以参考一下CCMenu,看看人家是怎么做的,你一下子就会明白了!

实现精灵在选中和非选中状态下精灵呈现不同状态的效果

bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
	if ( !CCLayerColor::initWithColor(ccc4(125,125,125,255)))
    {
        return false;
    }

    CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	//添加背景图片
	CCSprite * background = CCSprite::create("background.jpg");
	background->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	this->addChild(background,0);

    //为俩张图片进行初始化
	this->m_normalSprite = CCSprite::create("spriteNormal.png");
	this->m_selectedSprite = CCSprite::create("spriteSelected.png");

	this->m_normalSprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	this->m_selectedSprite->setPosition(ccp(visibleSize.width/2,visibleSize.height/2));
	//将正常状态下的图片的原始位置保存一下
	this->m_currentPoint = m_normalSprite->getPosition();

	this->addChild(m_normalSprite);
	this->addChild(m_selectedSprite);
	//将选中状态的图片设置为不要显示
	this->m_selectedSprite->setVisible(false);

	//开启触摸
	this->setTouchEnabled(true);

    return true;
}

void HelloWorld::registerWithTouchDispatcher()
{
	CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0,true);
}
//实现ccTouchBegan()函数
bool HelloWorld::ccTouchBegan(CCTouch * touch,CCEvent * pEvent)
{
	CCPoint selectPoint = touch->getLocation();
	CCRect spriteRect = this->m_selectedSprite->boundingBox();
	//当点中图片的时候设置另一张图片显示,点在了图片的其他区域则显示正常状态下的图片
	if(spriteRect.containsPoint(selectPoint))
	{
		this->m_selectedSprite->setVisible(true);
		this->m_normalSprite->setVisible(false);
		return true;
	}
	else
	{
		this->m_selectedSprite->setVisible(false);
		this->m_normalSprite->setVisible(true);
	}
	return false;
}
//设置图片跟随手指移动
void HelloWorld::ccTouchMoved(CCTouch * touch,CCEvent * pEvent)
{
	CCPoint nowPoint = touch->getLocation();
	CCPoint prePoint = touch->getPreviousLocation();
	CCPoint direction = ccpSub(nowPoint,prePoint);
	this->m_selectedSprite->setPosition(ccpAdd(m_selectedSprite->getPosition(),direction));
}
//结束状态的处理,改成你自己想要的状态
void HelloWorld::ccTouchEnded(CCTouch * touch,CCEvent * pEvent)
{
	CCPoint endPoint = touch->getLocation();
	//这个是那个框的位置
	 CCRect rect=CCRectMake(330,130,60,60);
	 if(rect.containsPoint(endPoint))
	 {
		 this->m_selectedSprite->setPosition(ccp(330+30,130+30));
		 this->m_normalSprite->setVisible(true);
		 this->m_selectedSprite->setVisible(true);
		 this->m_currentPoint = this->m_selectedSprite->getPosition();
	 }
	 else
	 {
		 this->m_selectedSprite->setVisible(false);
		 this->m_normalSprite->setVisible(true);
		 this->m_selectedSprite->setPosition(this->m_currentPoint);
	 }
}