Skip to content

Instantly share code, notes, and snippets.

@joeke80215
Created November 16, 2018 01:48
Show Gist options
  • Save joeke80215/2f8a0e01d92e29c27e4c980903e4dfb8 to your computer and use it in GitHub Desktop.
Save joeke80215/2f8a0e01d92e29c27e4c980903e4dfb8 to your computer and use it in GitHub Desktop.
Cocos2dx Sprite drop and drag
#include "example.h"
USING_NS_CC;
// createScene create scene for main scene
Scene* ExampleScene ::createScene()
{
return ExampleScene ::create();
}
// init on "init" you need to initialize your instance
bool ExampleScene ::init()
{
//////////////////////////////
// 1. super init first
if (!Scene::init())
{
return false;
}
auto visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// 初始化sprite
_spriteToMove = Sprite::create("Example.png");
// sprite 位置置中
_spriteToMove->setPosition(Point(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
// 將sprite加入到ExampleScene
this->addChild(_spriteToMove);
// 創建觸控監聽器
EventListenerTouchOneByOne *listener = EventListenerTouchOneByOne::create();
// 利用CC_CALLBACK_2綁定函數
listener->onTouchBegan = CC_CALLBACK_2(MainScene::onTouchBegan,this);
listener->onTouchMoved = CC_CALLBACK_2(MainScene::onTouchMoved,this);
// 加入監聽至事件分配
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
return true;
}
// onTouchBegan 必須實作否則會報錯
bool ExampleScene ::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
return true;
};
// 利用每次的變化量設定sprite位置
void ExampleScene ::onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event)
{
_spriteToMove->setPosition(_spriteToMove->getPosition() + touch->getDelta());
};
#ifndef __Example_SCENE_H__
#define __Example_SCENE_H__
#include "cocos2d.h"
class ExampleScene : public cocos2d::Scene
{
public:
static cocos2d::Scene* createScene();
virtual bool init();
CREATE_FUNC(ExampleScene );
// 需要綁定的函數
bool onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event);
void onTouchMoved(cocos2d::Touch *touch, cocos2d::Event *event);
private:
// 目標sprite
cocos2d::Sprite *_spriteToMove;
};
#endif // __Example_SCENE_H__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment