首页 > 代码库 > cocos2dx 3.x(点击屏幕移动精灵,拖动精灵)不需要写回调函数

cocos2dx 3.x(点击屏幕移动精灵,拖动精灵)不需要写回调函数

 1 //
 2 //  MainScene.cpp
 3 //  helloworld
 4 //
 5 //  Created by apple on 16/9/19.
 6 //
 7 //
 8 
 9 #include "MainScene.hpp"
10 Scene * MainScene::createScene()
11 {
12      auto scene = Scene::create();
13     //创建层
14     MainScene *layer = MainScene::create();
15     scene->addChild(layer);
16     return scene;
17 }
18 bool MainScene::init(){
19     if (!Layer::init()) {
20         return false;
21     }
22     
23     
24     sprite = Sprite::create("hu.png");
25     sprite ->setPosition(50, 50);
26     sprite->setAnchorPoint(Vec2(0.5, 0.5));
27     this->addChild(sprite);// 添加到层
28     
29   
30     
31     //声明
32     auto listener1 = EventListenerTouchOneByOne::create();
33     listener1->setSwallowTouches(true);
34     
35     //通过 lambda 表达式 直接实现触摸事件的回掉方法
36     listener1->onTouchBegan = [](Touch* touch, Event* event){
37         auto target = static_cast<Sprite*>(event->getCurrentTarget());
38         
39         Point locationInNode = target->convertToNodeSpace(touch->getLocation());
40         Size s = target->getContentSize();
41         Rect rect = Rect(0, 0, s.width, s.height);
42         
43         if (rect.containsPoint(locationInNode))
44         {
45             log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y);
46             target->setOpacity(180);//点击的时候精灵颜色变暗,255为最大值,0最小
47             return true;
48         }
49         return false;
50     };
51     
52     
53     
54     listener1->onTouchMoved = [](Touch* touch, Event* event){
55         auto target = static_cast<Sprite*>(event->getCurrentTarget());
56         target->setPosition(target->getPosition() + touch->getDelta());
57     };
58     
59     listener1->onTouchEnded = [=](Touch* touch, Event* event){
60         auto target = static_cast<Sprite*>(event->getCurrentTarget());
61         log("sprite onTouchesEnded.. ");
62         target->setOpacity(255);//手势松开时使精灵恢复原来的颜色
63     };
64     
65     
66     //将触摸事件绑定到精灵身上
67     _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite);
68     _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite);
69     _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite);
70     
71     return true;
72 }

 

cocos2dx 3.x(点击屏幕移动精灵,拖动精灵)不需要写回调函数