由于您似乎只关心触摸与您的_player 对象的距离,我会将半径检测逻辑移至您的_player 对象并使用SKRegion 来处理它。
注意: 如果您需要知道您的触摸是否在多个节点的半径内,那么您可能需要使用this question 中的方法。 p>
要使用SKRegion 来确定您的触摸是否在_player 的某个半径内,请将SKRegion 实例添加到您的_player 对象并使用您想要的半径对其进行初始化。在[_player init] 或任何对您的项目最有意义的地方:
self.touchRegion = [[SKRegion alloc] initWithRadius:radius];
然后添加一个方法来确定一个点是否在该区域内:
- (BOOL)pointIsInTouchRegion:(CGPoint)point {
return [self.touchRegion containsPoint: point];
}
接下来将您的 touchesMoved 方法更改为:
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
if (touches.count == 1)
{
UITouch *touch = [touches anyObject];
CGPoint point = [self locationInNode:_player]; // NOTE: It's important to use _player here!
if ([_player pointIsInTouchRegion: point]) {
[_player runAction:[SKAction moveTo:[[touches anyObject] locationInNode:self] duration:0.01]];
}
}
}
注意: 在[self locationInNode:_player]; 中使用_player 至关重要,因为您的SKRegion 将在_player 节点的坐标系中定义。
还有一点需要注意:您实际上不必将所有这些逻辑都放在_player 中,这正是我的做法。您可以轻松地将 SKRegion 存储在场景的类中,然后直接调用 [region containsPoint: point]。
更新:iOS 7 方法
对 iOS 7 执行此操作的主要区别在于,您需要存储您感兴趣的实际半径而不是 SKRegion(因为它仅在 iOS 8 中可用),然后在 @ 中自己进行计算987654342@。
因此,在_player 中,将您的触摸半径设置为您之前设置touchRegion 的位置:
self.touchRadius = radius
然后更改pointIsInTouchRegion: 方法,让它进行实际距离计算。
- (BOOL)pointIsInTouchRegion:(CGPoint)point {
CGPoint centerOfNode = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0); // NOTE: If this is in an SKSpriteNode, you might want to use self.anchorPoint instead
CGFloat distanceToCenter = return hypotf(point.x - centerOfNode.x, point.y - centerOfNode.y);
return (distanceToCenter <= self.radius);
}
touchesMoved 中的代码不需要任何更改。