cocos2dX 学习笔记——触摸事件、键盘事件、重力事件

今天练习一下触摸、键盘、重力响应。话不多说,都在代码里

 

.h

#ifndef _SCENE$_
#define _SCENE$_

#include "cocos2d.h"
USING_NS_CC;
class FourthScene :public cocos2d::CCLayer {

public:
    virtual bool init();
    static cocos2d::CCScene * createScene();
    CREATE_FUNC(FourthScene);
    void EnterFourthScene(Ref * ref);

    Sprite * sprite1;

    void onTouchesBegan(const std::vector& touches, Event *unused_event);

    void onTouchesMoved(const std::vector& touches, Event *unused_event);

    void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event);

    void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);

    virtual void onAcceleration(Acceleration* acc, Event* unused_event);
    
};


#endif // !_SCENE$_

cocos2dX 学习笔记——触摸事件、键盘事件、重力事件_第1张图片

 

.cpp   多点触摸和重力 需要打包实验 ,电脑上测不出来。

#include "fourthScene.h"
#include "cocos2d.h"
#include "HelloWorldScene.h"

USING_NS_CC;

cocos2d::CCScene * FourthScene::createScene()
{
    CCScene * scene = CCScene::create();
    FourthScene * layer = FourthScene::create();
    scene->addChild(layer);
    return scene;
}

bool FourthScene::init()
{
    if (!Layer::init())
    {
        return false;
    }

    Label *label1 = Label::createWithSystemFont("fourthScene",
        "calibri.ttf",
        20,
        Size::ZERO,
        TextHAlignment::CENTER,
        TextVAlignment::TOP
        );
    label1->setPosition(Point(300, 600));
    this->addChild(label1);


    //单点触摸;
    Size size = Director::getInstance()->getVisibleSize();
    //创建精灵;
    sprite1 = Sprite::create("da.png");
    sprite1->setPosition(size.width/2,size.height/2);
    sprite1->setScale(2);
    //设置tag;
    sprite1->setTag(10);
    this->addChild(sprite1);
    //注册监听;
    auto listener1 = EventListenerTouchOneByOne::create();
    //阻止往下传递;
    listener1->setSwallowTouches(true);
    listener1->onTouchBegan = [](Touch* touch, Event* event) {
        //获取事件绑定的精灵  获取触摸目标;
        auto target1 = static_cast(event->getCurrentTarget());
        //auto target1 = dynamic_cast(event->getCurrentTarget());
        //获取触摸点;  getLocation() 获取单击坐标 基于3D;
        //Point pos1 = target1->convertToNodeSpace(touch->getLocation());
        //getLocationInView()  获取单击坐标 屏幕坐标系的坐标;
        Point pos1 = Director::getInstance()->convertToGL(touch->getLocationInView());
        //convertToUI()  将屏幕坐标转为cocos2dx的坐标; 标准坐标系是以左上角为原点 而cocos2d以左下角为原点
        //Director::getInstance()->convertToUI(pos1);
        
        ////获取目标的轮廓大小;
        //Size s = target1->getContentSize();
        ////区域位置;
        //Rect rect = Rect(0,0,s.width,s.height);

        //判断触摸点是否在目标轮廓区域内;
        //if (rect.containsPoint(pos1))
        //{
        //    
        //    target1->setPosition(touch->getLocation());
        //    return true;
        //}
        //else
        //{
        //    return false;
        //}

        //检测是否触摸到精灵;
        if (target1->getBoundingBox().containsPoint(pos1))
        {
            //设置这个绑定到的精灵的透明度;
            target1->setOpacity(100);
            return true;
        }
        
        return false;
    };

    listener1->onTouchMoved = [=](Touch * touch, Event * event) {
    //拖动精灵;
        auto target1 = static_cast(event->getCurrentTarget());
        target1->setPosition(touch->getLocation());
    };

    listener1->onTouchCancelled = [=](Touch * touch,Event * event) {
        CCLOG("onTouchCancelled");
        sprite1->setOpacity(255);
        sprite1->setPosition(Point(300,400));
    };
    
    listener1->onTouchEnded = [=](Touch * touch,Event *event) {
        auto target2 = dynamic_cast(event->getCurrentTarget());
        target2->setPosition(Point(size.width / 2, size.height / 2));
        sprite1->setOpacity(255);
        CCLOG("onTouchEnded");
    };
    //将精灵添加到事件监听器中;
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite1);


    //多点触摸;
    Sprite *sprite2 = Sprite::create("ming.png");
    sprite2->setPosition(Point(size.height / 3, size.width / 2));
    this->addChild(sprite2);
    sprite2->setScale(2.5f);
    
    //注册监听;
    auto listener2 = EventListenerTouchAllAtOnce::create();
    listener2->onTouchesBegan = CC_CALLBACK_2(FourthScene::onTouchesBegan,this);
    listener2->onTouchesMoved = CC_CALLBACK_2(FourthScene::onTouchesMoved,this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener2, sprite2);


    //注册键盘监听;
    auto listener3 = EventListenerKeyboard::create();

    //第一种  需要在头文件中声明方法;
    listener3->onKeyPressed = CC_CALLBACK_2(FourthScene::onKeyPressed,this);

    listener3->onKeyReleased = CC_CALLBACK_2(FourthScene::onKeyReleased,this);

    //第二种;
    /*listener3->onKeyPressed = [=](EventKeyboard::KeyCode code,Event * event) {
        switch (code)
        {
        case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
        {
            sprite1->setRotation(30);
        }
            break;
        case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
            break;
        case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_A:
            break;
        case cocos2d::EventKeyboard::KeyCode::KEY_CAPITAL_B:
            break;

        default:
            break;
        }
    };
*/
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener3,this);


    //重力感应事件;
    //开启重力感应;
    this->setAccelerometerEnabled(true);
    auto listener4 = EventListenerAcceleration::create(CC_CALLBACK_2(FourthScene::onAcceleration,this));
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener4,this);


    return true;
}

void FourthScene::EnterFourthScene(Ref * ref)
{
    Director::getInstance()->replaceScene(TransitionFadeBL::create(1, HelloWorld::createScene()));
}

void FourthScene::onTouchesBegan(const std::vector& touches, Event * unused_event)
{
    CCLOG("began");
}

void FourthScene::onTouchesMoved(const std::vector& touches, Event * unused_event)
{
    auto sprite3 = static_cast(unused_event->getCurrentTarget());
    //缩放;
    if (touches.size()>1)
    {
        auto distance1 = touches[0]->getPreviousLocation().distance(touches[1]->getPreviousLocation());
        auto distance2 = touches[0]->getLocation().distance(touches[1]->getLocation());
        float scale = sprite3->getScale()*(distance2/distance1);
        scale = MIN(2,MAX(0.5,scale));
        sprite3->setScale(scale);
    }
    else
    {
        log("11");
    }

}

void FourthScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event * event)
{
    if (keyCode==EventKeyboard::KeyCode::KEY_A)
    {
        auto target = dynamic_cast(event->getCurrentTarget());
    std:: srand((unsigned)time(nullptr));
        int  rotate = std::rand()%10;
        //float rotate = MIN(10,MAX(20,90));
        CCLOG("%d num",rotate);
        sprite1->setRotation(-45*rotate);
    }
}

void FourthScene::onKeyReleased(EventKeyboard::KeyCode keyCode, Event * event)
{
    sprite1->setRotation(0);
}

//加速度计的回调函数;
void FourthScene::onAcceleration(Acceleration * acc, Event * unused_event)
{
    //通过tag获取sprite;
    Sprite * _sprite = (Sprite *)this->getChildByTag(10);
    if (_sprite)
    {
        //获取sprite坐标;
        Vec2 vec = _sprite->getPosition();
        //;
        float x = vec.x;
        float y = vec.y;
        //获取移动距离;
        float posx = acc->x * 10;
        float posy = acc->y * 10;
        _sprite->setPosition(Vec2(x + posx, y + posy));
    }

}

cocos2dX 学习笔记——触摸事件、键盘事件、重力事件_第2张图片

 

你可能感兴趣的:(cocos2dX)