Cocos2d-iphone 為sprite添加雙擊的事件響應

來源:互聯網
上載者:User

這篇文章介紹兩種方式處理cocos2d中的雙擊事件響應。

在iOS中使用UITapGestureRecognizer ,很容易就可以添加雙擊事件處理,但是在cocos2d中無法直接向sprite添加UITapGestureRecognizer,所以就要做一些處理。

說明:我現在是想向一個sprite 添加一個雙擊的事件響應。

第一種方法是比較簡單的,使用touch中的tapCount這個屬性就可以判斷是tap的次數。

代碼如下:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{        for (UITouch *touch in touches) {                if ([touch tapCount] == 1) {            NSLog(@"single tap!");        }        else if ([touch tapCount] == 2) {            NSLog(@"double tap!");        }        }}


這雷根據tapCount獲知是單擊和雙擊,然後再由touch擷取到touch的座標點,有這個座標點再和我們要添加雙擊事件的sprit做碰撞檢測,就是做CGRectContainsPoint()的判斷,那麼就可以將雙擊事件定位到我們要的sprite。

下面介紹第二種方法。

這裡我們還是要使用到UITapGestureRecognizer,但是添加的時候有一點技巧。


 UITapGestureRecognizer *doubleTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];        doubleTapGesture.numberOfTapsRequired = 2;        [[[CCDirector sharedDirector] view] addGestureRecognizer:doubleTapGesture];

-(void)tapAction:(UITapGestureRecognizer *)recognizer {        NSLog(@"double tap");    //這樣擷取到的座標位置是以左上方為原點的座標系    CGPoint doubleTapPoint = [recognizer locationInView:recognizer.view];    //通過轉換,將座標系換成是以左下角為原點的座標系    doubleTapPoint = [[CCDirector sharedDirector] convertToGL:doubleTapPoint];        NSLog(@"tap point = %@",NSStringFromCGPoint(doubleTapPoint));        for (CCSprite *sprite in spriteArray) {        //做碰撞檢測        if (CGRectContainsPoint(sprite.boundingBox, doubleTapPoint)) {        }    }}

和第一種方法一樣,我們也要通過碰撞檢測定位到雙擊是到哪一個sprite。





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.