Как я могу использовать жесты смахивания в cocos2d-js?

Я изучаю, как использовать жесты смахивания в cocos2d-js и обнаружил, что в cocos2d используется UISwipeGestureRecognizer. Но я не смог найти его для cocos2d-js.

Жесты в cocos2d

А также для cocos2d-x в github:

CCGestureRecognizer

Для cocos2d-js я нашел только

        cc.eventManager.addListener({
            event: cc.EventListener.TOUCH_ALL_AT_ONCE,
            onTouchesMoved:function (touches, event) {
                event.getCurrentTarget().processEvent(touches[0]);
            }
        }, this);

с дополнительными типами событий:

onTouchesBegan
onTouchesEnded
onTouchesCancelled

Это все, что есть в cocos2d-js для обнаружения свайпов влево, вправо, вверх, вниз?


person Michael    schedule 23.05.2014    source источник


Ответы (3)


Вот мое решение, протестированное для cocos2d-js 3.0a2:

   if( true || 'touches' in cc.sys.capabilities ) { // touches work on mac but return false
        cc.eventManager.addListener(cc.EventListener.create({
            event: cc.EventListener.TOUCH_ALL_AT_ONCE,
            onTouchesBegan: function(touches, event) {
                console.log("onTouchesBegan!");

                var touch = touches[0];
                var loc = touch.getLocation();

                self.touchStartPoint = {
                    x: loc.x,
                    y: loc.y
                };

                self.touchLastPoint = {
                        x: loc.x,
                        y: loc.y
                };
            },

            onTouchesMoved: function(touches, event) {
                var touch = touches[0];
                var loc = touch.getLocation(),
                    start = self.touchStartPoint;

                // check for left
                if( loc.x < start.x - self.touchThreshold ) {
                    // if direction changed while swiping left, set new base point
                    if( loc.x > self.touchLastPoint.x ) {
                        start = self.touchStartPoint = {
                                x: loc.x,
                                y: loc.y
                        };
                        self.isSwipeLeft = false;
                    } else {
                        self.isSwipeLeft = true;                        
                    }
                }

                // check for right
                if( loc.x > start.x + self.touchThreshold ) {
                    // if direction changed while swiping right, set new base point
                    if( loc.x < self.touchLastPoint.x ) {
                        self.touchStartPoint = {
                                x: loc.x,
                                y: loc.y
                        };
                        self.isSwipeRight = false;
                    } else {
                        self.isSwipeRight = true;                       
                    }
                }

                // check for down
                if( loc.y < start.y - self.touchThreshold ) {
                    // if direction changed while swiping down, set new base point
                    if( loc.y > self.touchLastPoint.y ) {
                        self.touchStartPoint = {
                                x: loc.x,
                                y: loc.y
                        };
                        self.isSwipeDown = false;
                    } else {
                        self.isSwipeDown = true;                        
                    }
                }

                // check for up
                if( loc.y > start.y + self.touchThreshold ) {
                    // if direction changed while swiping right, set new base point
                    if( loc.y < self.touchLastPoint.y ) {
                        self.touchStartPoint = {
                                x: loc.x,
                                y: loc.y
                        };
                        self.isSwipeUp = false;
                    } else {
                        self.isSwipeUp = true;                      
                    }
                }

                self.touchLastPoint = {
                        x: loc.x,
                        y: loc.y
                };
            },

            onTouchesEnded: function(touches, event){
                console.log("onTouchesEnded!");

                var touch = touches[0],
                    loc = touch.getLocation()
                    size = self.size;

                self.touchStartPoint = null;

                if( !self.isSwipeUp && !self.isSwipeLeft && !self.isSwipeRight && !self.isSwipeDown ) {
                    if( loc.y > size.height*0.25 && loc.y < size.height*0.75 ) {
                        (loc.x < size.width*0.50)? self.isTouchLeft = true : self.isTouchRight = true;
                    } else if( loc.y > size.height*0.75 ) {
                        self.isTouchUp = true;
                    } else {
                        self.isTouchDown = true;
                    }
                }

                self.isSwipeUp = self.isSwipeLeft = self.isSwipeRight = self.isSwipeDown = false;

                //location.y = self.size.height;
                //event.getCurrentTarget().addNewTileWithCoords(location);
            }
        }), this);
    } else {
        cc.log("TOUCH_ALL_AT_ONCE is not supported");
    }
person Michael    schedule 24.05.2014
comment
this.touchThreshold не определен. Подскажите, что это за .touchThreshold? - person Sudhakar; 22.05.2015
comment
@Sudhakar Это значение в пикселях. Я думаю, я использовал 10 для этого. Точно сказать не могу. Но в любом случае это зависит от ваших потребностей. Просто попробуйте разные... - person Michael; 22.05.2015

Вот мое решение в cocos2d-js

var cambaglayer = cc.Layer.extend({
                              ctor:function () {




                              this._super();
                              var size = cc.winSize;

                              touchCounter = 0;
                              if( true || 'touches' in cc.sys.capabilities ) {


                              cc.eventManager.addListener(cc.EventListener.create({
             event: cc.EventListener.TOUCH_ALL_AT_ONCE,
             onTouchesBegan: function(touches, event) {
             console.log("onTouchesBegan!");
             touchMenu();
             var touch = touches[0];
             var loc = touch.getLocation();
             this.touchStartPoint = {
             x: loc.x,
             y: loc.y
             };
             this.touchLastPoint = {
             x: loc.x,
             y: loc.y
             };
             },
             onTouchesMoved: function(touches, event) {
             var touch = touches[0];
             var loc = touch.getLocation(),
             start = this.touchStartPoint;
             console.log("onTouchesMoved!");
             console.log("onTouchesMoved!"+ touchThreshold);
             if( loc.x < start.x - touchThreshold ) {
             console.log("left!");
             if( loc.x > this.touchLastPoint.x ) {
             start = this.touchStartPoint = {
             x: loc.x,
             y: loc.y
             };
             this.isSwipeLeft = false;
             } else {
             this.isSwipeLeft = true;
             cc.log("swiping left side") 
             }
             }
             if( loc.x > start.x + touchThreshold ) {
             console.log("right!");

             if( loc.x < this.touchLastPoint.x ) {
             this.touchStartPoint = {
             x: loc.x,
             y: loc.y
             };
             this.isSwipeRight = false;
             } else {
             this.isSwipeRight = true;
             console.log("Swiping Right side");
             }
             }
             this.touchLastPoint = {
             x: loc.x,
             y: loc.y
             };
             },
             }
             ), this);
                              } else {
                              cc.log("TOUCH_ALL_AT_ONCE is not supported");
                              }
                              return true;
                              }
                              });
person kalpesh    schedule 27.08.2015

Не полный ответ, но: вы можете просто получить начальную позицию касания на onTouchesBegan и конечную позицию на onTouchesEnded и угадать направление салфетки, вычитая позиции и глядя, изменились ли X или Y больше всего (и в каком разделе).

Если вы ищете более мощный распознаватель жестов, чем просто вверх/вниз/влево/вправо, все, о чем я могу думать, это отослать вас к это пример проекта, использующего распознаватель жестов доллара от supersuracoon, хотя следует отметить, что это старый код (v2.2.2?) и менеджер событий немного отличается в cocos2d-html5 v3, поэтому он будет вероятно, потребуется некоторая работа над вашим текущим уровнем.

person Sebastián Vansteenkiste    schedule 23.05.2014