0

我在 a 中有一些小精灵(宽度/高度),CCLayer我想检测其中哪些被触摸。我使用以下代码。

- (BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLocation = [self convertTouchToNodeSpace:touch];

    CGRect rect = sprite.boundingBox;

    // i am doing this because of the small size of the sprites, 
    // so it would be more easy to detect if a sprite is taped and then move it.
    if (rect.size.width > rect.size.height) {
        rect.size.width *= 2.5;
        rect.size.height *= 5;
        rect.origin.y -= rect.size.height / 2;

    } else {
        rect.size.width *= 5;
        rect.size.height *= 2.5;
        rect.origin.x -= rect.size.width / 2;
    }

    CCSprite *s = nil;
    for (CCSprite *sprite in [self children]) {
        if (CGRectContainsPoint(rect, touchPoint)) {
            s = sprite;
            break;
        }
    }

    if (s != nil) {
        // do something here
    }

    return YES;
}

除非两个精灵彼此非常接近(不重叠),否则一切正常。然后由于它们之间的距离很小,检测到错误的精灵。

知道我该如何纠正吗?

4

1 回答 1

1

如果您试图扩大矩形,使其中心保持在原来的位置,您应该使用:

    rect.origin.y -= (rectFinalHeight - rectOriginalHeight) / 2;

    rect.origin.y -= (rectFinalWidth - rectOriginalWidth) / 2;

这将是:

if (rect.size.width > rect.size.height) {
    rect.size.width *= 2.5;
    rect.size.height *= 5;
    rect.origin.y -= rect.size.height * 4 / 2;

} else {
    rect.size.width *= 5;
    rect.size.height *= 2.5;
    rect.origin.x -= rect.size.width * 4 / 2;
}

IMO,您应该在两种情况下都沿两个轴调整矩形原点(不仅在一种情况下沿 x 轴,在另一种情况下沿 y 轴),否则您的矩形将不会居中。但是你更了解你想要做什么,在这里......

于 2013-03-30T12:09:37.207 回答