Siriss
Siriss

Reputation: 3767

SpriteKit - Random Sprite generation in only half the screen

I am trying to place a random object off screen in the X axis and have it scroll across the screen in just the top half (Y axis) of the screen. The phone is in landscape.

The scrolling is working fine, but I keep getting objects created in positions higher than the screen height. Here is my code based on this question.

- (CGPoint) randomPointWithinContainerSize:(CGSize)containerSize forViewSize:(CGSize)size
{
    CGFloat yRange = containerSize.height - size.height;

    CGFloat minY = (containerSize.height/2 - yRange) / 2;

    int randomY = (arc4random() % (int)floorf(yRange)) + minY;
    return CGPointMake(self.size.width + 100,randomY);//randomX,
}

the self.size.width + 100 is adding half of my sprite.

Here is my position code:

sprite.position = [self randomPointWithinContainerSizeGround:self.scene.size forViewSize:sprite.frame.size];

Again, I want it to scroll across just the top half of the screen and not get created outside the screen's Y axis bounds.

How do I do it?

Upvotes: 0

Views: 191

Answers (1)

0x141E
0x141E

Reputation: 12753

This should work...

   #define ARC4RANDOM_MAX      0x100000000
    - (CGPoint) randomPointWithinContainerSize:(CGSize)containerSize forViewSize:(CGSize)size
    {
        // Ensure that the sprite's y value is within the container
        CGFloat yRange = containerSize.height/2 - size.height;
        CGFloat minY = (containerSize.height + size.height) / 2;
        CGFloat randomY = ((double)arc4random()/ARC4RANDOM_MAX) * yRange + minY;

        return CGPointMake(containerSize.width+size.width,randomY);
    }

Upvotes: 1

Related Questions