LoginSignup
5
5

More than 5 years have passed since last update.

タッチイベントを使う基本(Cocos Code IDE, Lua言語)

Posted at

Cocos Code IDEを使ってLua言語でタッチイベントを使う基本をまとめました。
プロジェクトの新規作成されるサンプルアプリを参考にしています。

実行環境、IDE Cocos2d-xバージョン 言語
Cocos Code IDE Mac OS X 1.0.0-RC2 Cocos2d-x V3.2 Lua言語

サンプルコード

プロジェクトの新規作成で作成されるGameScene.luaのGameScene.create()を書き換えます。

GameScene.lua/GameScene.create
function GameScene.create()
    local scene = GameScene.new()

    -- タッチイベントで呼ばれる関数
    local function onTouchBegan(touch, event)
        local location = touch:getLocation()
        print(string.format("location = %0.2f, %0.2f", location.x, location.y)) -- この行は確認のためログに表示するためのもので、必要ありません。
        return true -- beganはtrueを返すようにする
    end

    local function onTouchMoved(touch, event)
    end

    local function onTouchEnded(touch, event)
    end

    -- タッチイベントの登録
    local listener = cc.EventListenerTouchOneByOne:create()
    listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN )
    listener:registerScriptHandler(onTouchMoved, cc.Handler.EVENT_TOUCH_MOVED )
    listener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED )

    local eventDispatcher = scene:getEventDispatcher()
    eventDispatcher:addEventListenerWithSceneGraphPriority(listener, scene)

    return scene
end

実行しても画面上は真っ黒な画面だけで何も表示されませんが、画面をタッチ(クリック)すると座標位置がログに表示されます。

解説

タッチイベントで呼び出される関数の準備

タッチイベントで呼び出される関数を準備します。関数名は何でもいいですが、ここではサンプルプログラムにならっています。

-- タッチイベントで呼ばれる関数
local function onTouchBegan(touch, event)
    return true -- beganはtrueを返すようにする
end

local function onTouchMoved(touch, event)
end

local function onTouchEnded(touch, event)
end

イベントの登録

タッチイベント時に上記の関数を呼ぶように登録します。

-- タッチイベントの登録
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(onTouchBegan, cc.Handler.EVENT_TOUCH_BEGAN )
listener:registerScriptHandler(onTouchMoved, cc.Handler.EVENT_TOUCH_MOVED )
listener:registerScriptHandler(onTouchEnded, cc.Handler.EVENT_TOUCH_ENDED )

local eventDispatcher = scene:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, scene)

タッチした座標の取得

タッチした座標の取得はonTouchBegan内等で、

local location = touch:getLocation()
print(string.format("location = %0.2f, %0.2f", location.x, location.y)) -- この行は確認のためログに表示するためのもので、必要ありません。

とします。

タッチイベントの削除

登録したタッチイベントの削除方法です。

-- listenerのイベントを削除する時
eventDispatcher:removeEventListener(listener)
-- sceneのすべてのイベントを削除する時は、
--eventDispatcher:removeEventListenersForTarget(scene)
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5