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

 //
// MainScene.cpp
// helloworld
//
// Created by apple on 16/9/19.
//
// #include "MainScene.hpp"
Scene * MainScene::createScene()
{
auto scene = Scene::create();
//创建层
MainScene *layer = MainScene::create();
scene->addChild(layer);
return scene;
}
bool MainScene::init(){
if (!Layer::init()) {
return false;
} sprite = Sprite::create("hu.png");
sprite ->setPosition(, );
sprite->setAnchorPoint(Vec2(0.5, 0.5));
this->addChild(sprite);// 添加到层 //声明
auto listener1 = EventListenerTouchOneByOne::create();
listener1->setSwallowTouches(true); //通过 lambda 表达式 直接实现触摸事件的回掉方法
listener1->onTouchBegan = [](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget()); Point locationInNode = target->convertToNodeSpace(touch->getLocation());
Size s = target->getContentSize();
Rect rect = Rect(, , s.width, s.height); if (rect.containsPoint(locationInNode))
{
log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y);
target->setOpacity();//点击的时候精灵颜色变暗,255为最大值,0最小
return true;
}
return false;
}; listener1->onTouchMoved = [](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
target->setPosition(target->getPosition() + touch->getDelta());
}; listener1->onTouchEnded = [=](Touch* touch, Event* event){
auto target = static_cast<Sprite*>(event->getCurrentTarget());
log("sprite onTouchesEnded.. ");
target->setOpacity();//手势松开时使精灵恢复原来的颜色
}; //将触摸事件绑定到精灵身上
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, sprite);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite); return true;
}
上一篇:VS Code编辑器插件整理及配置设定


下一篇:Android 快速选择联系人