Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

09 | Cocos2D-JS | How to use touch event #10

Open
Gurigraphics opened this issue Apr 29, 2018 · 0 comments
Open

09 | Cocos2D-JS | How to use touch event #10

Gurigraphics opened this issue Apr 29, 2018 · 0 comments

Comments

@Gurigraphics
Copy link
Owner

Gurigraphics commented Apr 29, 2018

09 | How to use touch event

Game.layers.js

Edit the Game.layers.js

Add to sprite that has been extended the listener.

In a complex project the ideal is to create another file Game.listeners.js to isolate the events in a separate file. And then import into projects.json

    var sprite2 = cc.Sprite.extend({
        ctor:function() {
            this._super();
            this.initWithFile("HelloWorld.png");
            this.setScale(0.5);
            cc.eventManager.addListener(listener.clone(), this);
        }
    });
    
    var listener = cc.EventListener.create({
         event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true,
         onTouchBegan: function (touch, event) {
             sprite2 = event.getCurrentTarget();
             var location = sprite2.convertToNodeSpace(touch.getLocation());
             var targetSize = sprite2.getContentSize();
             var targetRectangle = cc.rect(0, 0, targetSize.width, targetSize.height);
             if (cc.rectContainsPoint(targetRectangle, location)) {
     
                layer.removeChild(sprite2);      
                var tag = sprite2.getTag();     
     
             }
         }
    });

The same listener can be added for different sprites.
To know which sprite was clicked use the tags:
var tag = sprite2.getTag ();

Events:

onTouchBegan: on press
onTouchEnded: on release
onTouchMoved: on press and move
onTouchCancelled: on canceling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant