Search code examples
iosxcodesprite-kitgravityskspritenode

How do i keep falling spritenodes within the view?


i am trying to make an iphone game similar to the raywenderlich : sprite Kit tutorial for Beginners Turorial. I am trying to make this in portait mode however, instead of the landscape mode which is used in the tutorial. I used this code and adjusted it so that the sprites fall from the top of the screen to the bottom, but sometimes the sprite are half outside the view or even more.

http://www.raywenderlich.com/42699/spritekit-tutorial-for-beginners

This is what i got:

SKSpriteNode * monster = [SKSpriteNode spriteNodeWithImageNamed:@"AcornFinal.png"];

// Determine where to spawn the monster along the X axis
int minX = self.frame.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX + minX;
int actualX = (arc4random() % + rangeX);

// Random position along the X axis as calculated above
// This describe from which way the acorns move
// - means moving from top to the right and + means moving from the top to the left
monster.position = CGPointMake(actualX,self.frame.size.height);
[self addChild:monster];

// Determine speed of the monster
int minDuration = 2.0;
int maxDuration = 4.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;



// Create the actions
SKAction * actionMove = [SKAction moveTo:CGPointMake(actualX,-monster.size.height) duration:actualDuration];
SKAction * actionMoveDone = [SKAction removeFromParent];
[monster runAction:[SKAction sequence:@[actionMove, actionMoveDone]]];

So I believe that the problem probably is in these four lines of code :

// Determine where to spawn the monster along the X axis
int minX = self.frame.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX + minX;
int actualX = (arc4random() % + rangeX);

How can i fix this error>?

EDIT

solution was to change the first four lines into

int minX = monster.size.width;
int maxX = self.frame.size.width - monster.size.width;
int rangeX = maxX - minX;
int actualX = (arc4random() % rangeX)+minX;

Solution

  • If the idea is to keep the monsters within the horizontal-bounds of the screen your math seems somewhat of. If the anchor point of the sprite is 0.5, 0.5 and the scene-size equals the screen I believe it should be:

    int minX = monster.size.width / 2; 
    int maxX = self.frame.size.width - monster.size.width;
    int x = (arc4random() % + maxX) +  minX;