1

我将解释我的代码的一部分。我有在屏幕上向下移动的 Spritenodes(图像)。

SKTexture* Squaretexture = [SKTexture textureWithImageNamed:@"squaregreen"];
SquareTexture.filteringMode = SKTextureFilteringNearest;
Square = [SKSpriteNode spriteNodeWithTexture:SquareTexture];
Square.name = @"square";
.
.
.

[_objects addChild:Square];

_objects是一个SKNode并且Square是一个SKSpriteNode。现在有我的代码:每一秒都有一个方块,它来自“屏幕上方”并且正在移动到底部。(屏幕上还有一个以上的正方形)。

现在我想要这个:当我触摸一个正方形时,它应该被“删除”或隐藏,但只有我触摸的那个。使用我的代码,当我触摸时,所有方块都会被删除或什么都没有。我尝试使用 removefromparent 和 removechild,但我无法解决它。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode: self];
    SKNode *node = [self nodeAtPoint:location];

    NSLog(@"Point in myView: (%f,%f)", location.x, location.y);
    if ([node.name isEqualToString:@"Square"]) {
        [Square removeFromParent];
        [Square removeAllChildren];
    }    
}

你有什么建议我该怎么做?感谢您的回答。穆罕默德

4

1 回答 1

1

你几乎是对的。诀窍是您需要为您创建的每个对象(精灵)拥有一个唯一标识符,然后将这些对象存储在一个数组中以供以后使用。

下面的代码创建了 5 个精灵并赋予它们唯一的名称:Sprite-1、Sprite-2 等...

每当注册触摸时,它会提取触摸节点的名称,在数组中搜索匹配的对象,从视图中删除对象,最后从数组中删除对象。

请注意,我的示例代码基于横向视图。

#import "MyScene.h"

@implementation MyScene
{
    NSMutableArray *spriteArray;
    int nextObjectID;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        spriteArray = [[NSMutableArray alloc] init];
        nextObjectID = 0;

        // create 5 sprites
        for (int i=0; i<5; i++)
        {
             SKSpriteNode *mySprite = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(30, 30)];
             nextObjectID ++; // increase counter by 1
             mySprite.name = [NSString stringWithFormat:@"Sprite-%i",nextObjectID]; // add unique name to new sprite
             mySprite.position = CGPointMake(50+(i*70), 200);
            [spriteArray addObject:mySprite];
            [self addChild:mySprite];
        }
    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     UITouch *touch = [touches anyObject];
     CGPoint location = [touch locationInNode: self];
     SKNode *node = [self nodeAtPoint:location];

     NSLog(@"touched node name: %@",node.name);
     NSLog(@"objects in spriteArray: %lu",(unsigned long)[spriteArray count]);

     NSMutableArray *discardedItems = [NSMutableArray array];
     for(SKNode *object in spriteArray)
     {
        if([object.name isEqualToString:node.name])
        {
           [object removeFromParent];
           [discardedItems addObject:object];
        }
    }
    [spriteArray removeObjectsInArray:discardedItems];

    NSLog(@"objects in spriteArray: %lu",(unsigned long)[spriteArray count]);

}

-(void)update:(CFTimeInterval)currentTime
{
    //
}

@end
于 2014-05-01T21:32:42.343 回答