触屏

新建工程:testTouch

修改HelloWorldScene.h

#ifndef __HELLOWORLD_SCENE_H__

#define __HELLOWORLD_SCENE_H__


#include "cocos2d.h"

using namespace cocos2d;

class HelloWorld : public cocos2d::CCLayer

{

public:

    // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer)

    virtual bool init();


    // there's no 'id' in cpp, so we recommend to return the class instance pointer

    static cocos2d::CCScene* scene();   


    // preprocessor macro for "static create()" constructor ( node() deprecated )

    CREATE_FUNC(HelloWorld);

    

    //重写触屏回调函数

    virtual bool ccTouchBegan(CCTouch* touch,CCEvent* event);

    virtual void ccTouchMoved(CCTouch* touch,CCEvent* event);

    virtual void ccTouchEnded(CCTouch* touch,CCEvent* event);

    

    //重写生命周期函数

    virtual void onEnter();

    virtual void onExit();

    

    //Menu&Back

    virtual void keyBackClicked();

    virtual void keyMenuClicked();

    

    

};


#endif // __HELLOWORLD_SCENE_H__


修改HelloWorldScene.cpp

#include "HelloWorldScene.h"

#include "SimpleAudioEngine.h"


using namespace cocos2d;

using namespace CocosDenshion;


CCScene* HelloWorld::scene()

{

    // 'scene' is an autorelease object

    CCScene *scene = CCScene::create();

    

    // 'layer' is an autorelease object

    HelloWorld *layer = HelloWorld::create();


    // add layer as a child to scene

    scene->addChild(layer);


    // return the scene

    return scene;

}


// on "init" you need to initialize your instance

bool HelloWorld::init()

{

    //////////////////////////////

    // 1. super init first

    if ( !CCLayer::init() )

    {

        return false;

    }


    CCSprite *spr=CCSprite::create("Icon.png");

    spr->setPosition(ccp(150, 150));

    addChild(spr,0,922);

    

    //back&menu

    setKeypadEnabled(true);


    

    return true;

}



//重写触屏回调函数

bool HelloWorld::ccTouchBegan(CCTouch* touch,CCEvent* event)

{

    CCLOG("ccTouchBegan");

    return true;

}

void HelloWorld::ccTouchMoved(CCTouch* touch,CCEvent* event)

{

    CCLOG("ccTouchMoved");

}

void HelloWorld::ccTouchEnded(CCTouch* touch,CCEvent* event)

{

    CCLOG("ccTouchEnded");

    //获取离开屏幕时对应的坐标

    CCPoint point=touch->getLocation();

    

    //获取到精灵tag=922的精灵

    CCSprite *sp=(CCSprite *)this->getChildByTag(922);

    //暂停所有动作

    sp->stopAllActions();

    //执行move动作到用户离开时的位置

    sp->runAction(CCMoveTo::create(1, point));

}


//重写生命周期函数

void HelloWorld::onEnter()

{

    CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, false);

    CCLayer::onEnter();

}

void HelloWorld::onExit()

{

    CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);

    CCLayer::onExit();

}


//Menu&Back

void HelloWorld::keyBackClicked()

{

    CCLog("Back clicked!");

}

void HelloWorld::keyMenuClicked()

{

     CCLog("Menu clicked!");

}


你可能感兴趣的:(触屏)