cocos2d-x 3.2 移动游戏背景和精灵

1,先新增监听事件

auto listener = EventListenerTouchOneByOne::create();
	listener->setSwallowtouches(true);
	listener->onTouchBegan = CC_CALLBACK_2(StartGame::onTouchBegan,this);
	listener->onTouchMoved = CC_CALLBACK_2(StartGame::onTouchMoved,this);
	listener->onTouchEnded = CC_CALLBACK_2(StartGame::onTouchEnded,this);
	_eventdispatcher->addEventListenerWithSceneGraPHPriority(listener,this);

2,监听的方法回调函数实现
bool StartGame::onTouchBegan(Touch* touch,Event* event)
{
    Point touchLocation = this->convertTouchToNodeSpace(touch);
    this->selectSpriteForTouch(touchLocation);
    return true;
}

void StartGame::onTouchMoved(Touch* touch,Event* event)
{
	Point touchLocation = this->convertTouchToNodeSpace(touch);
    Point oldTouchLocation = touch->getPrevIoUsLocation();
    oldTouchLocation = this->convertToNodeSpace(oldTouchLocation);
    Point translation = touchLocation - oldTouchLocation;//获取移动的距离

	cclog("touchLocation--------------------%d-------%d",touchLocation.x,touchLocation.y);
	cclog("oldTouchLocation--------------------%d-------%d",oldTouchLocation.x,oldTouchLocation.y);
	cclog("translation--------------------%d-------%d",translation.x,translation.y);
	
    this->boundLayerPos(translation);//背景移动函数
    //this->panForTranslation(translation);//精灵移动函数

}

void StartGame::onTouchEnded(Touch* touch,Event* event)
{
}


3,方法实现

这个事背景事件,在init里面加载一张背景图片

void StartGame::boundLayerPos(Point newtouch)
{
    Size winSize = Director::getInstance()->getWinSize();
	Point newPos = this->getPosition() + newtouch;
	auto map = getChildByTag(102); //这里获取背景图片

    newPos.x = MIN(newPos.x,0);
    newPos.x = MAX(newPos.x,-map->getContentSize().width+winSize.width);

    newPos.y = MIN(newPos.y,0);
	newPos.y = MAX(newPos.y,-map->getContentSize().height + winSize.height);

    this->setPosition(newPos);
}

精灵移动方法实现

在init里面加载一个精灵

void StartGame::panForTranslation(Point translation)
{
	auto sprite = getChildByTag(101);//获取精灵
    Point newPos = sprite->getPosition() + translation;
    sprite->setPosition(newPos);
    
}

这就ok了


精灵或者是背景图片移动都是在触屏监听事件的onTouchMoved(Touch* touch,Event * event)里面获取原触屏点和移动以后的触屏点,得到他们的差值,给精灵或者背景图片重新定位setPosition(Point * point),就完成了背景和精灵的移动(背景图片要判断边界值得)


注意,Node可通过函数getBoundingBox返回精灵的边界矩形。这比你自己手动计算精灵的边界矩形要好多了。因为,第一,它更简单;第二,它考虑了精灵的位置坐标变换。(比如锚点变了,要执行相应的矩阵变换,具体可以参考源代码,这些就不再细说了。)

点击选中的时候可以先让精灵做一些动作,这里是闪烁

void StartGame::selectSpriteForTouch(Point touchLocation)
{
	auto sprite = getChildByTag(101);
   
    if ( sprite->getBoundingBox().containsPoint(touchLocation) )
    {
            auto blink = CCBlink::create(2.0f,5);
			sprite->runAction(blink);
    }
   
   
}

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...