Search code examples
sprite-kitcollision-detectionskscene

SKScene detect collision before adding to parent


I am working on a game using Sprite Kit and it involves a ball hitting a target (goal). When the ball makes contact with the goal I want the goal to be removed and added again in a different location. That all works but the problem is more often than not (it seems like) the goal spawns right on top of or intersecting the ball. How would I go about preventing this? Thanks in advance and tell me if I need to post my didBeginContact code.


Solution

  • You can avoid this issue by adding the goal at a new location that is relative to the ball's position. First, add these functions...

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

    and then this to your 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);