简体   繁体   中英

SpriteKit Adding Sprites on Collision Detection

I am detecting collision between two sprites and on collision I am trying to add more sprites in the scene. The following method is invoked when the collision is detected.

-(void) contactBetweenGreenBallAndRedBall:(SKPhysicsContact *) contact
{   
    if([self isLevelCompleted])
    {
        [self addRedBallsToScene:10];
    }

}

// add red balls to the scene
-(void) addRedBallsToScene:(int) numberOfRedBalls
{
    for(int i = 1; i <= numberOfRedBalls; i++)
    {
        int x = arc4random() % (int) self.size.width;
        int y = arc4random() % (int) self.size.height;

        RedBall *redBall = [[RedBall alloc] init];
        redBall.name = @"redball";
        redBall.position = CGPointMake(x, y);

        [self addChild:redBall];

        [_redBalls addObject:redBall];

        [redBall.physicsBody applyImpulse:CGVectorMake(5.0, -10.0f)];
    }
}

Even though I add redBall to the scene I never see it. The scene never shows the newly added red ball.

UPDATE: I noticed that the sprites are getting added but for some reason they are added at 0,0 Why is that?

Your code

int x = arc4random() % (int) self.size.width;
int y = arc4random() % (int) self.size.height;

is valid and works. Your issue is not the actual code but the location of the self.size... being called where the return values do not reflect the screen size. Try calling the code from another location. To test, place manual values instead of the random ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM