SKScene在添加到父级之前检测到冲突

时间:2014-07-22 15:00:11

标签: sprite-kit collision-detection skscene

我正在使用Sprite Kit进行游戏,它涉及一个球击中目标(目标)。当球与球门接触时,我希望球门被移除并再次添加到不同的位置。这一切都有效,但问题往往是(似乎)目标产生在球的顶部或交叉球。我该如何防止这种情况?提前致谢并告诉我是否需要发布我的didBeginContact代码。

1 个答案:

答案 0 :(得分:1)

您可以通过在相对于球的位置的新位置添加目标来避免此问题。首先,添加这些功能......

static inline CGFloat skRandf() {
    return rand() / (CGFloat) RAND_MAX;
}

static inline CGFloat skRand(CGFloat low, CGFloat high) {
    return skRandf() * (high - low) + low;
}

然后再到你的didBeginContact ......

    CGFloat goalWidth = goal.size.width;
    CGFloat goalHeight = goal.size.height;

    CGFloat maxX = self.frame.size.width - goalWidth;
    CGFloat maxY = self.frame.size.height - goalHeight;

    CGFloat dx = MAX(maxX-kMinDistanceFromBall-_ball.position.x, 0) + MAX(ball.position.x-kMinDistanceFromBall, 0);
    CGFloat dy = MAX(maxY-kMinDistanceFromBall-_ball.position.y, 0) + MAX(ball.position.y-kMinDistanceFromBall, 0);

    CGFloat newX = ball.position.x + MIN(maxX-ball.position.x, kMinDistanceFromBall) + skRand(0, dx);
    CGFloat newY = ball.position.y + MIN(maxY-ball.position.y, kMinDistanceFromBall) + skRand(0, dy);

    if (newX > maxX) {
        newX -= maxX;
    }

    if (newY > maxY) {
        newY -= maxY;
    }

    goal.position = CGPointMake (newX+goalWidth/2, newY+goalHeight/2);