Cocos2dx-lua Touch Events in user events with base content

Source: Internet
Author: User
Tags addchild diff event listener lua touch

This blog is a presentation that describes using COOCS2DX Lua with touch events. For Main.lua files, look in the previous articles in the same series.

The underlying content will no longer be explained, and this article will focus on the content. Use the steps to create the listener you want (touch listener, Keyboard listener). Listener settings are swallowed. The listener sets the type of event to listen on (CC. Handler.event_touch_began), as well as the corresponding callback function. Create the dispatcher and register the event listener. use case

SIZE=CC. Director:getinstance (): Getvisiblesize () Local Testscene=class ("Test", function () return CC. Scene:create () end)--Initialize function testscene:ctor () print ("ctor running") End Function Testscene:c
   reate () local scene=testscene.new ()--Create the scene.
   Local Layer=testscene:createlayer ()--Create layer. Scene:addchild (Layer)--add a layer to the scene return scene--return to scenes End Function Testscene:c Reatelayer () Local layer=cc. Layer:create ()--Create scene spritetag=100 local sp=cc. Sprite:create ("Helloworld.png") sp:setposition (CC.P (size.width/2,size.height/2+200)) Layer:addChild (sp,10, Spritetag) spritetag1=101 local sp1=cc. Sprite:create ("Helloworld.png") sp1:setposition (CC.P (size.width/2-100,size.height/2+50)) Layer:addChild (sp1,10, SPRITETAG1)--The parameters of the callback function are the touch object, and the node object that is bound.
    The order cannot be wrong. Local function Touchbegan (touch,event) print ("Touchbegan")--Gets the bound SPRite object, only useful when registering with Scenegraph local node=event:getcurrenttarget () Local pos=node:converttonodespace (Touch:getlo cation ()) local size=node:getcontentsize () local rect=cc.rect (0,0,size.width,size.height)--Determine if touch points touch
        To the object being monitored. If Cc.rectcontainspoint (Rect,pos) then print ("pos.x=": Pos.x, "Pos.y". POS.Y) Print ("Node tag="). Node:gettag ()) Node:runaction (CC.
           Scaleto:create (0.5,1.5))--you need to return true to call the next two functions. Return True end return False end local function touchended (touch,event) print ("touchended ") local Node=event:getcurrenttarget () node:runaction (CC. Scaleto:create (0.5,1.0)) End Function touchmoved (touch,event) print ("touchmoved") Local node=event : Getcurrenttarget () local nodex,nodey=node:getposition () local Diff=touch:getdelta () node:setposition (CC.P (NODEX+DIFF.X,NODEY+DIFF.Y)) End--Create a single touch listener local ListenERS=CC.
   Eventlistenertouchonebyone:create ()--sets whether to engulf the event. Listeners:setswallowtouches (True)--registers the callback function and the event property Listeners:registerscripthandler (TOUCHBEGAN,CC. Handler.event_touch_began) Listeners:registerscripthandler (touchmoved,cc. handler.event_touch_moved) Listeners:registerscripthandler (touchended,cc. handler.event_touch_ended)--Create the event dispatcher local EVENTDISPATCHER=CC. Director:getinstance (): Geteventdispatcher ()--Once the listener is registered, it cannot be registered again. You can clone an identical listener using clone () Listener1=listeners:clone ()--The Sprite Object SP,SP1 Register event listener Eventdispatcher:addeventlistenerwithscenegra Phpriority (listeners, SP) eventdispatcher:addeventlistenerwithscenegraphpriority (LISTENER1,SP1)

Each event listener can only be added once, and Addeventlistenerwithscenegraphpriority and Addeventlistenerwithfixedpriority will set a registration ID when the event listener is added. Once the registration ID is set, the listener can no longer be used to register for other event listeners, so a new listener object needs to be obtained using the Clone () function to register the new listener object. how to get the object being touched

When registering the listener with addeventlistenerwithscenegraphpriority (), you can use Event:getcurrenttarget () to get the bound sprite object. Such as:

Local function OnTouch (touch,event) 
   local node=event:getcurrenttarget ()
End

When registering listeners with addeventlistenerwithfixedpriority (), you cannot use Event:getcurrenttarget () to get the bound sprite object. Because when using fixedpriority, there is no bound sprite at all. So this time, can only use Layer:getchildbytag (number) one to get, and then to judge.

The code follows, adds a custom Istap (), and modifies the callback function of the touch event:

    --Use the fixed registered event callback function case. --Customize to determine if the touch point is within the Sprite local function Istap (node,touch) local size=node:getcontentsize () local rect=cc.rect (0, 0,size.width,size.height) Local Pos=node:converttonodespace (Touch:getlocation ()) If Cc.rectcontainspoint (rec      
          T,POS) Then-returns true if the touch point is inside the sprite. 
        Return True end end local function Touchbegan (touch,event)-use Layer:getchildbytag (tag) to get a node.
        How many node you need to get the number of node you need to determine. Local Node1=layer:getchildbytag (Spritetag) if Istap (Node1,touch) then Node1:runaction (CC. Scaleto:create (0.5,1.5)) return True End local Node2=layer:getchildbytag (SPRITETAG1) I F Istap (Node2,touch) then Node2:runaction (CC. Scaleto:create (0.5,1.25)) return True end return False end local function touchmoved ( touch,event) Local Node1=layer:getchildbytag (Spritetag) if Istap (Node1, touch) then print ("Node1 moved") local Diff=touch:getdelta () local Nodex,nodey=node1:ge
            Tposition () node1:setposition (CC.P (NODEX+DIFF.X,NODEY+DIFF.Y))--If you do not return a null value, the following conditions will also be executed
           -As a result, two sprites move together. Return end local Node2=layer:getchildbytag (SPRITETAG1) if Istap (Node2,touch) then Prin T ("node2222 moved") local Diff=touch:getdelta () local nodex,nodey=node2:getposition () nod E2:setposition (CC.P (NODEX+DIFF.X,NODEY+DIFF.Y)) return end end local EVENTDISPATCHER=CC.
Director:getinstance (): Geteventdispatcher ()--note that fixedpriority registered is used here. Eventdispatcher:addeventlistenerwithfixedpriority (listeners, 20)

As can be learned from the above, when using fixed, whether it is Touchbegan, or touchmoved, touchended all need A to get the Genie object to be judged , and then use a custom method Istap () a judgment. Precautions

The registration event is not registered on an Elf object at first, but the entire screen has a registration event. This means that the Touchbegan function can be triggered throughout the screen.

Because the entire screen will have registration events, Touchbegan should return false by default so that both Touchmove and touchended are not called. Then, in Touchbegan, determine whether the point is within the object scope, if there is any action on it, and then return True.

Listener objects are not only created one, you can create multiple. Just when an event listener is registered, it can no longer be registered, only with Listener:clone (), there is one need to note that using clone () there is no way to remove the listener, because there is no name.

When you use fixedpriority listeners, you need to remove manually after you add it, and scenegraphypriority Listener and node bindings are removed when node is destroyed.
_eventdispatcher:removeeventlistener (listener);

When the listener is removed, it will persist for listener:clone () if it is not removed. This will cause an error if you do not get a sprite in the listener's callback function. And for the use of listener ()->clone can not be removed as above, because it does not have a name, it is only cloned, unless all the listener is removed. Then the button can not be used for monitoring.

How to get the Sprite object and take action on it.
Use Scenegraphpriority to register an event, you can use Event:getcurrenttarget (), and get the target of the binding.
Registering events with fixtedpriority can only be obtained using the Layer:getchildbytag (Sprite tag Value). Unless it is a constant.

If you need to work with an object individually, consider using fixted to perform specific processing for a particular sprite. If you need to do the same with multiple objects, you can use scenegraphpriority. Because you can use Event:getcurrenttarget ()//To get the bound sprite in function processing

Scenegraph the sprite display priority as the event priority, the second parameter of Addchild (), the greater the ZOrder value, the greater the event priority.
The fixed event priority (the second parameter) registers the listener, and the event priority determines the priority of the event response, and the smaller the value, the higher the priority level.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.