0

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

    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 有关,或者是因为每个精灵都存在透明区域。我在这里缺少什么吗?

4

1 回答 1

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

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

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

为了确保这一点,您应该启用:

#define CC_SPRITE_DEBUG_DRAW 1

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

于 2013-02-05T02:26:22.680 回答