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

来源:互联网 发布:椭圆机品牌 知乎 编辑:程序博客网 时间:2024/04/30 05:56

1,先新增监听事件

?
1
2
3
4
5
6
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,监听的方法回调函数实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool StartGame::onTouchBegan(Touch* touch, Event* event)
{
    Point touchLocation = this->convertTouchToNodeSpace(touch);
    this->selectSpriteForTouch(touchLocation);
    returntrue;
}
 
voidStartGame::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);//背景移动函数
?
1
2
3
4
5
6
7
    //this->panForTranslation(translation);//精灵移动函数
 
}
 
voidStartGame::onTouchEnded(Touch* touch, Event* event)
{
}


3,方法实现

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
voidStartGame::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里面加载一个精灵

?
1
2
3
4
5
6
7
voidStartGame::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返回精灵的边界矩形。这比你自己手动计算精灵的边界矩形要好多了。因为,第一,它更简单;第二,它考虑了精灵的位置坐标变换。(比如锚点变了,要执行相应的矩阵变换,具体可以参考源代码,这些就不再细说了。)

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

?
1
2
3
4
5
6
7
8
9
10
11
12
voidStartGame::selectSpriteForTouch(Point touchLocation)
{
    auto sprite = getChildByTag(101);
    
    if( sprite->getBoundingBox().containsPoint(touchLocation) )
    {
            auto blink = CCBlink::create(2.0f,5);
            sprite->runAction(blink);
    }
    
    
}
0 0
原创粉丝点击