我将解释我的部分代码。我有Spritenodes(图像)谁在屏幕上向下移动。
SKTexture* Squaretexture = [SKTexture textureWithImageNamed:@"squaregreen"];
SquareTexture.filteringMode = SKTextureFilteringNearest;
Square = [SKSpriteNode spriteNodeWithTexture:SquareTexture];
Square.name = @"square";
.
.
.
[_objects addChild:Square];
_objects
是SKNode
,Square
是SKSpriteNode
。现在有我的代码:每隔一秒就有一个正方形,来自"在屏幕上#34;并且正在向底部移动。 (屏幕上还有一个以上的方块)。
现在我想要这个:当我触摸一个正方形时,应该"删除"或隐藏,但只有我触摸的人。用我的代码,当我触摸所有正方形被删除或没有。我尝试使用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];
}
}
你有什么建议我该怎么办? 谢谢你的回答。 穆罕默德
答案 0 :(得分: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