• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 无法获取ChildByTag

[复制链接]
菜鸟教程小白 发表于 2022-12-13 06:52:20 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在关注 Lynda.com iOS 教程,该教程使用 cocos2d(第 2 版)进行游戏开发。讲师使用以下代码使 Sprite 图像在触摸事件时增大。下面代码中的日志语句正在工作(即启用了触摸事件),但是当我单击模拟器时,图像并没有变大。原来这一行的痣是零

CCSprite *mole =  (CCSprite *)[self getChildByTag:1];

这是整个方法

- (void)ccTouchesBeganNSSet *)touches withEventUIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL: location ];
    CCLOG(@"touch happened at x: %0.2f y: %0.2f",location.x, location.y );
    CCSprite *mole =  (CCSprite *)[self getChildByTag:1];

    if (CGRectContainsPoint([mole boundingBox], location)) {
        [mole runAction:[CCSequence actions:
                         [CCScaleTo actionWithDuration:.25 scale:1.1],
                         [CCScaleTo actionWithDuration:.25 scale:1.0],
                         nil]];
    }
}

通过下面的 init 方法,痣出现在屏幕上。我假设上面的行 CCSprite *mole = (CCSprite *)[self getChildByTag:1]; 应该得到对小时候的痣的引用,但它显然不起作用。 p>

-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value
    if( (self=[super init])) {
        self.isTouchEnabled = YES;
        CGSize s = [[CCDirector sharedDirector] winSize];
        CCSprite *mole = [CCSprite spriteWithFile"mole.png"];
        mole.position = ccp(s.width/2,s.height/2);
        [self addChild:mole];
        mole.tag = 1;

        CCSprite *bg = [CCSprite spriteWithFile"bg.png"];
        bg.anchorPoint = ccp(0,0);
        [self addChild:bg z:-1];
    }
    return self;
}

你能从上面的代码中看出为什么这里的mole是nil吗?

 CCSprite *mole =  (CCSprite *)[self getChildByTag:1];

更新

HelloWorldLayer.h

#import <GameKit/GameKit.h>

// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"

// HelloWorldLayer
@interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>
{
}

// returns a CCScene that contains the HelloWorldLayer as the only child
+(CCScene *) scene;

@end

HelloWorldLayer.m

// Import the interfaces
#import "HelloWorldLayer.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#pragma mark - HelloWorldLayer

// HelloWorldLayer implementation
@implementation HelloWorldLayer

// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
    // 'scene' is an autorelease object.
    CCScene *scene = [CCScene node];

    // 'layer' is an autorelease object.
    HelloWorldLayer *layer = [HelloWorldLayer node];

    // add layer as a child to scene
    [scene addChild: layer];

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super's" return value
    if( (self=[super init]) ) {

        self.isTouchEnabled = YES;

        // create and initialize a Label
//      CCLabelTTF *label = [CCLabelTTF labelWithString"Hello World" fontName"Marker Felt" fontSize:64];
//
//      // ask director for the window size
//      CGSize size = [[CCDirector sharedDirector] winSize];
//
//      // position the label on the center of the screen
//      label.position =  ccp( size.width /2 , size.height/2 );
//      
//      // add the label as a child to this Layer
//      [self addChild: label];

        CGSize s = [[CCDirector sharedDirector] winSize];
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile"moles.plist"];
        CCSprite *mole = [CCSprite spriteWithSpriteFrameName"a0010.png"];
//      CCSprite *mole = [CCSprite spriteWithFile"mole.png"];
        mole.position = ccp(s.width/2,s.height/2);
        mole.scale = .25;
        //between 0 255
//        mole.opacity = 100;
        NSMutableArray *frames = [[NSMutableArray alloc] init];
        for (int i = 1; i <= 10; i++) {
            NSString *frameName = [NSString stringWithFormat"a%04i.png",i];
            [frames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:frameName]];
        }
        CCAnimation *a = [CCAnimation animationWithFrames:frames delay:1.0f/24.0f];
        [mole runAction:[CCAnimate actionWithAnimation:a restoreOriginalFrame:NO]];
        [self addChild: mole];


        CCSprite *bg = [CCSprite spriteWithFile"bg.png"];
        //supposed to fill whole screen but not

        //got next three lines from SO
    //stackoverflow.com/questions/12383228/how-to-set-background-image-for-the-entire-scene-in-cocos2d-xcode
        CGSize imageSize = bg.contentSize;
        bg.scaleX = s.width/ imageSize.width;
        bg.scaleY = s.height/ imageSize.height;

        bg.anchorPoint = ccp(0,0);
        [self addChild:bg z:-1];
        //
        // Leaderboards and Achievements
        // *

//      // Default font size will be 28 points.
//      [CCMenuItemFont setFontSize:28];
//      
//      // to avoid a retain-cycle with the menuitem and blocks
//      __block id copy_self = self;
//      
//      // Achievement Menu Item using blocks
//      CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString"Achievements" block:^(id sender) {
//          
//          
//          GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init];
//          achivementViewController.achievementDelegate = copy_self;
//          
//          AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//          
//          [[app navController] presentModalViewController:achivementViewController animated:YES];
//          
//          [achivementViewController release];
//      }];
//      
//      // Leaderboard Menu Item using blocks
//      CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) {
//          
//          
//          GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
//          leaderboardViewController.leaderboardDelegate = copy_self;
//          
//          AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//          
//          [[app navController] presentModalViewController:leaderboardViewController animated:YES];
//          
//          [leaderboardViewController release];
//      }];
//
//      
//      CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, nil];
//      
//      [menu alignItemsHorizontallyWithPadding:20];
//      [menu setPosition:ccp( size.width/2, size.height/2 - 50)];
//      
//      // Add the menu to the layer
//      [self addChild:menu];

    }
    return self;
}

//- (void)accelerometerUIAccelerometer *)accelerometer didAccelerateUIAcceleration *)acceleration
//{
//    acceleration.x
//}

- (void)ccTouchesBeganNSSet *)touches withEventUIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView: [touch view]];
    location = [[CCDirector sharedDirector] convertToGL: location ];
    CCLOG(@"touch happened at x: %0.2f y: %0.2f",location.x, location.y );
    CCSprite *mole =  (CCSprite *)[self getChildByTag:1 ];
    NSLog(@"mole %@", mole);
//    if (CGRectContainsPoint([mole boundingBox], location))
//    {
//        [mole runAction: [CCScaleBy actionWithDuration:.25 scale:1.1]];
//        
//    }
    if (CGRectContainsPoint([mole boundingBox], location)) {
        [mole runAction:[CCSequence actions:
                         [CCScaleTo actionWithDuration:.25 scale:1.1],
                         [CCScaleTo actionWithDuration:.25 scale:1.0],
                         nil]];
    }
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
    // in case you have something to dealloc, do it in this method
    // in this particular example nothing needs to be released.
    // cocos2d will automatically release all the children (Label)

    // don't forget to call "super dealloc"
    [super dealloc];
}

#pragma mark GameKit delegate

-(void) achievementViewControllerDidFinishGKAchievementViewController *)viewController
{
    AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
    [[app navController] dismissModalViewControllerAnimated:YES];
}

-(void) leaderboardViewControllerDidFinishGKLeaderboardViewController *)viewController
{
    AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
    [[app navController] dismissModalViewControllerAnimated:YES];
}
@end



Best Answer-推荐答案


  // set the tag value mole sprite in init method (HelloWorldLayer.m).

   CCSprite *mole = [CCSprite spriteWithSpriteFrameName:@"a0010.png"];
    //      CCSprite *mole = [CCSprite spriteWithFile:@"mole.png"];
    mole.position = ccp(s.width/2,s.height/2);
    mole.scale = .25;
    mole.tag=1;

关于ios - 无法获取ChildByTag,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22333445/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap