我正在试图弄清楚如何知道用户是否正在接触精灵。
我将我的代码简化为裸骨,在init上我创建了一个名为“button”的精灵,然后我试着知道用户何时触摸它/停止触摸。
这就是我现在正在尝试的事情:
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
self.backgroundColor = [SKColor colorWithRed:0 green:0 blue:0 alpha:1.0];
// Add button
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"button"];
sprite.name = @"button";
sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame));
[self addChild:sprite];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
SKNode *node = [self nodeAtPoint:location];
if ([node.name isEqualToString:@"button"]) {
NSLog(@"Started touch on sprite");
}
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
}
然而,虽然我可以判断按钮是否开始触摸,但我无法判断用户是否结束了触摸或移出了精灵(或者是副本)。我怎么能这样做?
答案 0 :(得分:0)
你也可以像这样节点的框架:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self.scene];
if (CGRectContainsPoint(sprite.frame, touchLocation))
{
// do something
}
}
答案 1 :(得分:0)
添加到属性:(允许您以各种方法访问它们)
@property (nonatomic) BOOL touchInSprite;
@property (nonatomic) SKSpriteNode * sprite;
@end
添加方法:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if ([self.sprite containsPoint: location])
self.touchInSprite = true;
else
self.touchInSprite = false;
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if ([self.sprite containsPoint: location])
{
self.touchInSprite = true;
}
else
{
self.touchInSprite = false;
//user stop touches it
}
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
if (self.startTouchValid == true)
{
//Perform action
}
}