定义用于触摸的精灵形状

时间:2012-01-25 20:56:37

标签: objective-c cocos2d-iphone shape ccsprite cgpath

我正在尝试使用此代码为我的精灵添加形状,这些都在NSArray中:

theSprites = [[NSMutableArray alloc] init];

CCSprite *sprite1 = [CCSprite spriteWithSpriteFrameName:@"sprite1"];
sprite1.position = ccp(winSize.width/2, sprite1.contentSize.height/2);
[self addChild:sprite1 z:3];
sprite1Path=CGPathCreateMutable();
CGPathMoveToPoint(sprite1Path, NULL, 0, 286);
CGPathAddLineToPoint(sprite1Path, NULL, 0, 0);
CGPathAddLineToPoint(sprite1Path, NULL, 768, 0);
CGPathAddLineToPoint(sprite1Path, NULL, 768, 208);
CGPathAddLineToPoint(sprite1Path, NULL, 356, 258);
CGPathCloseSubpath(sprite1Path);
[theSprites addObject:sprite1];

CCSprite *sprite2 = [CCSprite spriteWithSpriteFrameName:@"sprite2"];
sprite2.position = ccp(winSize.width/2, sprite2.contentSize.height/2);
[self addChild:sprite2 z:4];
sprite2Path=CGPathCreateMutable();
CGPathMoveToPoint(sprite2Path, NULL, 0, 254);
CGPathAddLineToPoint(sprite2Path, NULL, 0, 0);
CGPathAddLineToPoint(sprite2Path, NULL, 768, 0);
CGPathAddLineToPoint(sprite2Path, NULL, 768, 144);
CGPathAddLineToPoint(sprite2Path, NULL, 494, 168);
CGPathAddLineToPoint(sprite2Path, NULL, 204, 212);
CGPathCloseSubpath(sprite2Path);
[theSprites addObject:sprite2];

然后我试图指明只有 theSprites 是可移动的。我在cocos2d教程中创建了一个函数。

- (void)selectSprite:(CGPoint)touchLocation {
CCSprite *touchSprite = nil;
for (CCSprite *sprite in theSprites) {
  if (CGRectContainsPoint(sprite.boundingBox, touchLocation)) {            
    touchSprite = sprite;
    }  }  }

现在我堆叠了! 我不明白如何将CGRectContainsPoint更改为CGPathContainsPoint ... 我不知道如何用一个语句指定两个形状......或者创建if()if()constraction ...

1 个答案:

答案 0 :(得分:0)

我看到两个问题。首先,您需要将路径附加到精灵。您应该对CCSprite进行子类化并为其赋予boundingPath属性:

MySprite.h

@interface MySprite : CCSprite

@property (nonatomic) CGPath shapePath;

@end

MySprite.m

@implementation MySprite

@synthesize shapePath = _shapePath;

- (void)setShapePath:(CGPath)path {
    CGPathRetain(path);
    CGPathRelease(_shapePath);
    _shapePath = path;
}

- (void)dealloc {
    CGPathRelease(_shapePath);
    [super dealloc]; // if you're using ARC, omit this line
}

然后在创建精灵时设置shapePath属性:

MySprite *sprite1 = [MySprite spriteWithSpriteFrameName:@"sprite1"];
// ... blah blah blah all the stuff you did to init sprite1 and sprite1Path
CGPathCloseSubpath(sprite1Path);
sprite1.shapePath = sprite1Path;
[theSprites addObject:sprite1];

现在你可以像这样测试精灵中的触摸:

- (MySprite *)spriteAtPoint:(CGPoint)point {
    for (MySprite *sprite in theSprites) {
        CGPoint spriteOrigin = sprite.boundingBox.origin;
        CGPoint pointInSprite = CGPointMake(point.x - spriteOrigin.x, point.y - spriteOrigin.y);
        if (CGPathContainsPoint(sprite.shapePath, NULL, pointInSprite, false))
            return sprite;
        }
    }
}