簡體   English   中英

精靈觸摸檢測

[英]Sprite touch detection

有一個問題在這里。 我在(id)init函數中創建了幾個Sprite(帶有標簽),然后僅嘗試檢測觸摸了哪個Sprite? 我的init函數的代碼片段粘貼在下面。

    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"blue_sheet.plist"];
    //create a sprite batch node
    CCSpriteBatchNode *TrainerSprites = [CCSpriteBatchNode batchNodeWithFile:@"blue_sheet.png"];
    [self addChild:TrainerSprites z:1];

    //create a sprite from that node
    CCSprite *Horse = [CCSprite spriteWithSpriteFrameName:@"horse_blue.png"];
    [TrainerSprites addChild:Horse z:1 tag:1];
    //Horse.position = ccp(winSize.width/5, winSize.height/2);
    [Horse setScaleX: 138.5/Horse.contentSize.width];
    [Horse setScaleY: 80/Horse.contentSize.height];

    //create a sprite from that node
    CCSprite *Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"];
    [TrainerSprites addChild:Cow z:1 tag:2];
    //Cow.position = ccp(winSize.width/2, winSize.height/2);
    [Cow setScaleX: 126/Cow.contentSize.width];
    [Cow setScaleY: 100/Cow.contentSize.height];

    Horse.position = ccp(4*winSize.width/5, winSize.height/2);
    Cow.position = ccp(winSize.width/5, winSize.height/2);

    CGRect pos1 = CGRectMake(Cow.position.x, Cow.position.y, 200, 100);
    CGRect pos2 = CGRectMake(Horse.position.x, Horse.position.y, 200, 100);

    self.touchEnabled = YES;

一切看起來都很好……精靈將出現在它們應有的位置。 當我觸摸屏幕上的任意位置時,ccTouchBegan函數將觸發。 CGRect沒有看到任何事件,我想我需要確定分配的標簽觸發了哪一個。 是的,的確如此,我知道我缺少代碼,我只是無法在任何地方找到良好的可靠文檔,以實現該看似基本的ios功能。 我假設“ sprite觸摸檢測”代碼應駐留在ccTouchBegan函數內部? 真誠的感謝您的幫助或指導。 :)

可以檢測到精靈觸摸

在您的.h部分中聲明CCSprite *Cow

在.m部分使用
初始化方法

//create a sprite from that node
    Cow = [CCSprite spriteWithSpriteFrameName:@"cow_blue.png"];
    [TrainerSprites addChild:Cow z:1 tag:2];
    //Cow.position = ccp(winSize.width/2, winSize.height/2);
    [Cow setScaleX: 126/Cow.contentSize.width];
    [Cow setScaleY: 100/Cow.contentSize.height];

接觸開始的方法

 -(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {    
        UITouch * touch =[touches anyObject];
        CGPoint location=[touch locationInView:[touch view]];
        location =[[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint( [Cow boundingBox], location)) {

               /* CCScene *scene = [CCScene node];
                [scene addChild:[ClassicScene node]];
                [[CCDirector sharedDirector] replaceScene:scene];*/
            }

    }

另一種方法可能是CCSprite的子類並實現TargetedTouchDelegate

就像是:

@interface AnimalSprite:CCSprite<CCTargetedTouchDelegate>

這種方法的優點是,您無需在要添加精靈的圖層中進行大量的“ If”檢查。 該鏈接提供了您必須在orer中實現的方法才能實現協議,以及在何處以及如何向touch dispatcher注冊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM