玩家的飞机直接用Sprite来创建
代码:
GameLayer.h
Sprite * m_pPlayerPlane ;
GameLayer.cpp
m_pPlayerPlane = Sprite::create("myPlane.png") ; m_pPlayerPlane->setPosition(Vec2(screenSize.width / 2,screenSize.height / 2)) ; addChild(m_pPlayerPlane,ZORDER_PLAYER) ;
为游戏中的元素分层,这个是很必要的,所以,添加了zOrder
GameLayer.h
static const int ZORDER_BG = 0 ; static const int ZORDER_PLAYER = 10 ;
实现飞机的移动:
通过点击事件实现了飞机的移动,同时,限制飞机不能出屏幕。
auto lisener = EventListenerTouchOneByOne::create() ; lisener->onTouchBegan = [&](Touch *toch,Event * event) { auto target = dynamic_cast<Layer*>(event->getCurrentTarget()) ; auto loction = target->convertToNodeSpace(toch->getLocation()) ; m_touchBeginPos = loction ; return true ; } ; lisener->onTouchMoved = [&](Touch *toch,Event * event) { auto target = dynamic_cast<Layer*>(event->getCurrentTarget()) ; auto loction = target->convertToNodeSpace(toch->getLocation()) ; m_touchMovePos = loction ; Vec2 var = m_touchMovePos - m_touchBeginPos ; Vec2 pos = m_pPlayerPlane->getPosition() + var ; m_pPlayerPlane->setPosition(pos) ; if (m_pPlayerPlane->getPositionX() < m_pPlayerPlane->getBoundingBox().size.width / 2) { m_pPlayerPlane->setPositionX(m_pPlayerPlane->getBoundingBox().size.width / 2) ; } if (m_pPlayerPlane->getPositionX() > Director::getInstance()->getWinSize().width - m_pPlayerPlane->getBoundingBox().size.width / 2) { m_pPlayerPlane->setPositionX(Director::getInstance()->getWinSize().width - m_pPlayerPlane->getBoundingBox().size.width / 2) ; } if (m_pPlayerPlane->getPositionY() < m_pPlayerPlane->getBoundingBox().size.height / 2) { m_pPlayerPlane->setPositionY(m_pPlayerPlane->getBoundingBox().size.height / 2) ; } if (m_pPlayerPlane->getPositionY() > Director::getInstance()->getWinSize().height - m_pPlayerPlane->getBoundingBox().size.height / 2) { m_pPlayerPlane->setPositionY(Director::getInstance()->getWinSize().height - m_pPlayerPlane->getBoundingBox().size.height / 2) ; } m_touchBeginPos = loction ; } ; lisener->onTouchEnded = [&](Touch *toch,Event * event) { m_touchBeginPos = Vec2(0,0) ; m_touchMovePos = Vec2(0,0) ; } ; _eventDispatcher->addEventListenerWithSceneGraPHPriority(lisener,this) ;原文链接:https://www.f2er.com/cocos2dx/343545.html