CCLayer扩展和触摸实现?

时间:2014-03-22 16:15:57

标签: ios objective-c cocos2d-iphone cclayer

我做了一个CCLayer,它拥有CCSprite和两个CCLabelBMFont。我的目标是创建一个自定义的“按钮”,按下时按钮会缩小。我遇到了触摸和缩放这一层的问题。

首先是触摸,即使我像这样转换触摸,我也无法准确触摸图层边界框:

CGPoint currentTouchLocation = [self convertTouchToNodeSpace:touch];

触摸处理方式如下:

// Touching shop item?
if(CGRectContainsPoint([self boundingBox], currentTouchLocation)) {
    NSLog(@"Pressing item");
    mShopItemPushed = true;
    return true;
}

return false;

似乎CCLayer没有真实大小的boundingBox默认情况下它的内容所以我想我需要根据CCLayer内容覆盖一个?我有什么想法可以正确地做到这一点吗?

第二个问题是基于CCLayer的“按钮”缩放。如果我以某种方式使触摸处理工作,将图层缩小一半会导致缩放图层从原始位置移开数十个像素。没有设置锚点但是在缩放时仍然将图层移动到侧面并向上移动。我该如何防止这种行为?

以下是基于CCLayer的按钮的一些代码:

+(id) shopItem:(NSString*)fileName : (CGPoint)position : (NSString*)itemName : (int)itemPrice
{
    return [[[self alloc] initWithShopItemData:fileName:position:itemName:itemPrice] autorelease];
}

-(id) initWithShopItemData:(NSString*)fileName : (CGPoint)position : (NSString*)itemName : (int)itemPrice
{
    self = [super init];
    [self setPosition:position];

    mShopItemPushed = false;

    mPicture = [CCSprite spriteWithSpriteFrameName:fileName];
    [mPicture setPosition:CGPointMake(position.x - (3.0f * [DeviceSpecific cellSize]), position.y)];
    [self addChild:mPicture z:1];

    // Make price string
    NSString* price = [NSString stringWithFormat:@"%d", itemPrice];

    mItemPrice = [CCLabelBMFont labelWithString:price fntFile:[DeviceSpecific scoreAndCoinFont]];
    [mItemPrice setScale:0.5f];
    [mItemPrice setAnchorPoint:CGPointMake(1.0f, 0.5f)];
    [mItemPrice setPosition:CGPointMake(position.x + (3.5f * [DeviceSpecific cellSize]), position.y)];
    [self addChild:mItemPrice z:1];

    mItemName = [CCLabelBMFont labelWithString:itemName fntFile:[DeviceSpecific scoreAndCoinFont]];
    [mItemName setScale:0.5f];
    [mItemName setAnchorPoint:CGPointMake(0.0f, 0.5f)];
    [mItemName setPosition:CGPointMake(mPicture.position.x + [DeviceSpecific cellSize], mPicture.position.y)];
    [self addChild:mItemName z:1];

    self.isTouchEnabled = YES;

    return self;
}

[DeviceSpecific cellSize]只是一个测量单位,可以在不同的设备上保持正确的距离。

1 个答案:

答案 0 :(得分:0)

我通过基于此图层中项目的外部限制用rect覆盖boundingBox -function来解决这个问题。缩放问题仍然存在,所以我只是为接收到的触摸做了另一个指标。