【问题标题】:cocos2d Sprite contentSize Problemcocos2d Sprite contentSize 问题
【发布时间】:2009-07-10 17:46:50
【问题描述】:

我使用 spriteWithFile 方法定义了一个精灵,提供了一个 120 像素 x 30 像素的 .png

Sprite *trampoline = [Sprite spriteWithFile:@"trampoline.png"];     
[self addChild:trampoline];

当我将它添加到我的图层并定位它时,它就是我希望它出现在屏幕上的位置。

trampoline = [Trampoline node];
trampoline.position = ccp(160,15);
[self addChild:trampoline z:0 tag:1];

但是,它似乎没有 contentSize。以下 NSLog 语句:

NSLog(@"Content Size x:%f, y:%f", trampoline.contentSize.width,trampoline.contentSize.height);

给出以下读数:

2009-07-10 18:24:06.385 TouchSprite[3251:20b] Content Size x:0.000000, y:0.000000

我错过了什么吗?那不应该是 120.000000 x 30.000000

任何帮助将不胜感激。

问候,

丰富

【问题讨论】:

    标签: iphone cocos2d-iphone sprite


    【解决方案1】:

    这些线条是 Trampoline 类的一部分吗?

    Sprite *trampoline = [Sprite spriteWithFile:@"trampoline.png"];
    [self addChild:trampoline];
    

    根据我对 cocos2d 的有限经验,Sprite 的 contentSize 似乎只适用于实际属于该 Sprite 的内容,而不适用于该 Sprite 的所有子项。因此,在上面的示例中,在 log 语句中请求 contentSize 将不起作用,因为没有任何内容添加到 Trampoline 节点。但是,如果您要覆盖 Trampoline 类中的 contentSize 方法以返回实际加载图形的 Sprite 的 contentSize,那应该可以。

    这是我在当前正在开发的游戏中使用的 Sprite 的 sn-p,它说明了我在说什么:

    - (id) init
    {
    self = [super init];
    
    if (self != nil)
    {       
        self.textLabel = [Label labelWithString:@"*TEXT*"
                                       fontName:@"Helvetica"
                                       fontSize:18];
    
        [textLabel setRGB:0 :0 :0];
    
        textLabel.transformAnchor = CGPointZero;
        textLabel.position = CGPointZero;
        self.transformAnchor = CGPointZero;
    
        [self addChild:textLabel];
    }
    
    return self;
    }
    //
    
    - (CGSize) contentSize
    {
    return textLabel.contentSize;
    }
    

    这来自一个扩展 Sprite 的类。在我添加 contentSize 的覆盖之前,从另一个类中请求它会给我与你看到的相同的结果。现在我告诉它返回 textLabel 的内容大小,它就像我期望的那样工作。

    【讨论】:

      【解决方案2】:

      我假设 Trampoline 继承自 Sprite,然后继承自 Node。您正在使用创建节点的 [Trampoline node] 覆盖蹦床......但是 Trampoline 实现是否覆盖了节点方法以将您的 sprite 文件初始化到 Trampoline 节点?

      我认为您只是从该行返回一个空的 Node 类:

      trampoline = [Trampoline node];
      

      【讨论】:

      • 蹦床是 Sprite 的子类。行 trampoline = [Trampoline node] 正在初始化我的对象。 trampoline 不是空的,因为它设置了位置,并在我的屏幕上显示图像。
      猜你喜欢
      • 2014-05-12
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多