更新
我用以下代码解决了这个问题:
- (BOOL) isInside:(NSSet *)touches
{
//NSLog(@"%s", __PRETTY_FUNCTION__);
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
BOOL isInside = NO;
//NSLog(@"touchLocation %@", NSStringFromCGPoint(touchLocation) );
//NSLog(@"self.position %@", NSStringFromCGPoint(self.position) );
//NSLog(@"self.frame %@", NSStringFromCGRect(self.frame) );
//NSLog(@"self.size %@", NSStringFromCGSize(self.size) );
CGFloat atlX = fabsf(touchLocation.x);
CGFloat atlY = fabsf(touchLocation.y);
CGFloat lenX = self.size.width / 2;
CGFloat lenY = self.size.height / 2;
if ( (atlX <= lenX) && (atlY <= lenY) ) {
isInside = YES;
}
return isInside;
}
原始问题
这段代码我用于UIView的子类:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:self];
BOOL isInside = [self pointInside:touchLocation withEvent:event];
if (isInside)
{
if (NO == _isAlreadySelected)
{
[self setAppearanceSelected];
}
else
{
[self removeAppearanceSelected];
}
// more code
}
}
现在我的类是SKSpriteNode的子类,所以我想使用相同的逻辑:
CGPoint touchLocation = [touch locationInView:self];
BOOL isInside = [self pointInside:touchLocation withEvent:event];
但它不起作用,我无法编译。 (因为SKSpriteNode
)不存在这些方法
我设法将第一行更改为:
CGPoint touchLocation = [touch locationInNode:self];
问题
但是如何解决:
BOOL isInside = [self pointInside:touchLocation withEvent:event];
代表SKSpriteNode
更新 目前的解决方案得到了@ duci9y的帮助
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"%s", __PRETTY_FUNCTION__);
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
BOOL isInside = [self containsPoint:touchLocation];
NSLog(@"touchLocation %@", NSStringFromCGPoint(touchLocation) );
NSLog(@"self.position %@", NSStringFromCGPoint(self.position) );
NSLog(@"self.frame %@", NSStringFromCGRect(self.frame) );
if (isInside)
{
NSLog(@"INSIDE");
//self.texture = [SKTexture textureWithImage:_onImage];
}
else
{
NSLog(@"OUTSIDE");
//self.texture = [SKTexture textureWithImage:_offImage];
}
}
日志:
-[WOC_OnOffImageButton touchesBegan:withEvent:]
touchLocation {9.5, 18}
self.position {160, 440}
self.frame {{138, 414.5}, {44, 51}}
OUTSIDE
对我来说,看起来SpriteKit和UIView之间的坐标系存在一些问题。例如它们不是从同一点开始的(从左下角到左上角)。