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

前端之家收集整理的这篇文章主要介绍了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);
    }
   
   
}

猜你在找的Cocos2d-x相关文章