1

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

4

1 回答 1

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);
于 2014-07-22T16:55:12.013 回答