0

次のコードを使用して、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];

次に、スプ​​ライトのみが移動可能であることを指定しようとしています。cocos2d チュートリアルのような関数を作成しました。

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

そして今、私はスタックです!そして、CGRectContainsPoint を CGPathContainsPoint に変更する方法がわかりません... 1 つのステートメントで両方の形状を指定する方法がわかりません... または if () if () 構文を作成する方法がわかりません...

4

1 に答える 1

0

2 つの問題があります。まず、パスをスプライトにアタッチする必要があります。サブクラス化してプロパティ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;
        }
    }
}
于 2012-01-25T21:52:03.607 に答える