我正在尝试让 ccnodes(精灵、标签等)单独响应触摸事件......
我有以下代码:
@implementation CCNode (TouchDetection)
(BOOL)containsPoint:(CGPoint)point padding:(NSArray *)padding {
NSAssert(([padding count] == 4), @"padding must consist of [top, right, bottom, left] values!");
int paddingTop = [padding[0] integerValue];
int paddingRight = [padding[1] integerValue];
int paddingBottom = [padding[2] integerValue];
int paddingLeft = [padding[3] integerValue];
CGRect rect = CGRectMake(0, 0, paddingLeft + self.contentSize.width + paddingRight, paddingTop + self.contentSize.height + paddingBottom);
return CGRectContainsPoint(rect, locationInNodeSpace);
}
-(BOOL)containsTouch:(UITouch *)touch padding:(NSArray *)padding {
CCDirector* director = [CCDirector sharedDirector];
CGPoint locationGL = [director convertToGL:[touch locationInView:[[CCDirector sharedDirector] view]]];
return [self containsPoint:locationGL padding:padding];
}
@end
这很好用,除了在锚定的节点上,0,0 位于中心。这种实现显然在这种情况下不起作用,因为它与一个原点为 0,0 的矩形进行比较......所以,当我点击左侧的任何这些节点时,它们不会注册,因为 locationInNodeSpace 是负数,因此在矩形之外。
我将代码更改为:
(BOOL)containsPoint:(CGPoint)point padding:(NSArray *)padding {
NSAssert(([padding count] == 4), @"padding must consist of [top, right, bottom, left] values!");
int paddingTop = [padding[0] integerValue];
int paddingRight = [padding[1] integerValue];
int paddingBottom = [padding[2] integerValue];
int paddingLeft = [padding[3] integerValue];
float paddedWidth = paddingLeft + self.contentSize.width + paddingRight;
float paddedHeight = paddingTop + self.contentSize.height + paddingBottom;
CGRect rect = CGRectMake(-paddedWidth / 2, -paddedHeight / 2, paddedWidth, paddedHeight);
CGPoint locationInNodeSpace = [self convertToNodeSpace:point];
return CGRectContainsPoint(rect, locationInNodeSpace);
}
并且针对这些情况修复了它,但是现在对于 0,0 不在其中心的节点,它无法正常工作。
我会以错误的方式解决这个问题吗?最好让所有东西都固定在同一位置吗?
更新:
所以显然这个问题与锚点无关。我有一个 CCNode,其 contentSize 设置为 220,180。它的锚点是 0,0... 我添加了一些 NSLogging 来看看这里发生了什么。当我点击左下角时,我看到:
2013-09-28 09:24:11.205 [4101:c07] ================> anchor:{0, 0} location in node:{-77, -65.5} location in world:{1131, 1298.5} rect:{{0, 0}, {220, 180}} boundingBox:{{220, 170}, {220, 180}} padding: 0 0 0 0
它不会检测到这种触摸,因为节点空间中的位置是 NEGATIVE。CCNode 中心左侧和下方的所有内容都有一个负位置。
当我点击右上角时,我看到:
2013-09-28 09:24:12.175 [4101:c07] ================> anchor:{0, 0} location in node:{89, 64.5} location in world:{1297, 1428.5} rect:{{0, 0}, {220, 180}} boundingBox:{{220, 170}, {220, 180}} padding: 0 0 0 0
因此,无论如何,使用 CCNode 的边界框对我没有帮助。根据锚点修改矩形对我没有任何帮助。
我需要了解为什么我会得到负值...有人可以解释一下这种胡说八道吗?