展会信息港展会大全

cocos2d-x 3.2 移动游戏背景和精灵
来源:互联网   发布日期:2015-09-27 15:24:31   浏览:2883次  

导读: 1,先新增监听事件 auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(tr...

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);

}

}

赞助本站

人工智能实验室
相关内容
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港