在cocos2d中添加和触摸多个精灵

时间:2013-02-05 01:50:19

标签: objective-c cocos2d-iphone

我有一个类,我在其中添加了多个精灵,如下面的代码所示:

    CCSprite *b = [CCSprite spriteWithFile:@"b"];
    b.position = ccp(100, 160);

    CCSprite *b2 = [CCSprite spriteWithFile:@"b2.png"];
    b2.position = ccp(115, 150);

    CCSprite *b3 = [CCSprite spriteWithFile:@"b3.png"];
    b.position = ccp(200, 150);

    CCSprite *b4 = [CCSprite spriteWithFile:@"b4.png"];
    b4.position = ccp(220, 145);

    b.anchorPoint = ccp(0.98, 0.05);
    b2.anchorPoint = ccp(0.03, 0.05);
    b3.anchorPoint = ccp(0.03, 0.05);
    b4.anchorPoint = ccp(0.95, 0.05);

    [self addChild:b z:1 tag:1];
    [self addChild:b2 z:1 tag:2];
    [self addChild:b3 z:1 tag:3];
    [self addChild:b4 z:1 tag:4];

以下是触摸事件的代码:

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

//Swipe Detection - Beginning point
beginTouch = location;

for(int i = 0; i < [hairArray count]; i++)
{
    CCSprite *sprite = (CCSprite *)[hairArray objectAtIndex:i];
    if(CGRectContainsPoint([sprite boundingBox], location))
    {
        //selectedSprite is a sprite declared on the header file
        selectedSprite = sprite;
    }
}}

-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
//Move touched sprite
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

if(selectedSprite != nil)
{
    selectedSprite.position = ccp(location.x, location.y);
}}

-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//End point of sprite after dragged
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];

endTouch = location;
posX = endTouch.x;

//Minimum swipe length
posY = ccpDistance(beginTouch, endTouch);

[self moveSprite];}

现在,动作本身工作得很好,但我遇到的麻烦是,如果我想拖动b2,我必须首先拖动b3和b4。我不确定它是否与z-index有关,或者是因为每个sprite存在透明区域。这里有什么我想念的吗?

1 个答案:

答案 0 :(得分:1)

if(CGRectContainsPoint([sprite boundingBox], location))
{
  //selectedSprite is a sprite declared on the header file
  selectedSprite = sprite;
 }

在循环所有精灵时,一旦找到新的精灵,此代码就会更新当前选定的精灵。这意味着如果3个精灵重叠,您将得到所选的精灵是父亲节点数组中的最后一个。

你不能对订单做任何假设,所以这不是你想要的,你必须决定一个优先考虑精灵的政策。请注意,编辑anchorPoint可能会改变精灵的位置与边界框相比(因此边界框甚至在精灵之外)。

为了确保你应该启用:

#define CC_SPRITE_DEBUG_DRAW 1
ccConfig.h中的

。这将渲染精灵周围的边界框。