有些横板游戏中的主角需要既能往前跑,也能往后跑。
此时并不需要两套素材和两个精灵。只需要使用精灵的setFlippedX函数即可完成,并且使用精灵进行的动画也都可以实现水平翻转。
一个小例子如下:
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
SpriteFrameCache* frameCache = SpriteFrameCache::getInstance();
frameCache->addSpriteFramesWithFile("FlagZombie_default.plist", "FlagZombie_default.png");
zombie = Sprite::createWithSpriteFrameName("FlagZombie1.png");
zombie->setPosition(visibleSize.width / 2, visibleSize.height / 2);
addChild(zombie);
int iFrameNum = 12;
SpriteFrame* frame = nullptr;
Vector<SpriteFrame*> frameVec;
for (int i = 1; i <= iFrameNum; ++i){
frame = frameCache->getSpriteFrameByName(StringUtils::format("FlagZombie%d.png", i));
frameVec.pushBack(frame);
}
Animation* animation = Animation::createWithSpriteFrames(frameVec);
animation->setLoops(-1);
animation->setDelayPerUnit(0.1f);
Animate* action = Animate::create(animation);
zombie->runAction(action);
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
bool HelloWorld::onTouchBegan(Touch* touch, Event* event){
Size visibleSize = Director::getInstance()->getVisibleSize();
auto location = touch->getLocation();
if (location.x > visibleSize.width / 2){
//setFlippedX(true)会将精灵反转
zombie->setFlippedX(true);
}
else
{
//setFlippedX(false)会把精灵重新设置为原来的方向
zombie->setFlippedX(false);
}
return true;
}
程序如下图:
僵尸原来向左移动,点击屏幕右半边则使其改为向右移动,再点击左半边则会重新变为向左移动。