在HelloWorld项目中修改 1. HelloWorld.h #ifndef __HELLOWORLD_SCENE_H__ # define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" USING_NS_CC;class HelloWorld : public Scene{ public : static Scene* createScene (); virtual bool init(); void m
在HelloWorld项目中修改
1. HelloWorld.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
USING_NS_CC;
class HelloWorld : public Scene
{
public:
static Scene* createScene();
virtual bool init();
void menuCloseCallback(cocos2d::Ref* pSender);
virtual bool onTouchBegan(Touch *touch,Event *unused_event);
virtual void onTouchMoved(Touch *touch,Event *unused_event);
virtual bool onTouchEnd(Touch *touch,Event *unused_event);
CREATE_FUNC(HelloWorld);
private:
Sprite *m_touchItem;
bool m_bTouchedItem;
};
#endif // __HELLOWORLD_SCENE_H__
2.HelloWorld.cpp
#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
Scene *scene = Scene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
static void problemLoading(const char* filename)
{
printf("Error while loading: %s\n", filename);
printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n");
}
bool HelloWorld::init()
{
if ( !Scene::init() )
{
return false;
}
EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnd, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
this->setColor(Color3B(0, 255, 255));
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Size winSize = Director::getInstance()->getWinSize();
Sprite *pBg = Sprite::create("white.jpeg");
pBg->setPosition(Vec2(winSize.width/2, winSize.height/2));
pBg->setScale(4.5f);
addChild(pBg,0);
m_touchItem = Sprite::create();
m_touchItem->initWithFile("CloseNormal.png");
m_touchItem->setPosition(Vec2(winSize.width/2, winSize.height/2));
addChild(m_touchItem,1);
return true;
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
}
bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
Size spriteSize = m_touchItem->getContentSize();
Point pt = m_touchItem->getPosition();
Rect spriteRect = CCRectMake(pt.x - spriteSize.width/2, pt.y - spriteSize.height/2, spriteSize.width, spriteSize.height);
if (spriteRect.containsPoint(touch->getLocation()))
{
m_bTouchedItem = true;
}
return true;
}
void HelloWorld::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
if (m_bTouchedItem)
{
Point pos = touch->getLocation();
m_touchItem->setPosition(pos);
}
}
bool HelloWorld::onTouchEnd(cocos2d::Touch *touch, cocos2d::Event *unused_event)
{
if (m_bTouchedItem)
{
m_bTouchedItem = false;
}
return false;
}