Search code examples
sprite-kitgame-physics

SpriteKit Block positioning


I am trying to make a jump game in Xcode 5 with SpriteKit. First I want to spawn Blocks in a random position, but reachable for the 'human' in the game that is jumping. I got a 1. Block, that spawn at a set position. From this position, there should spawn a 2. Block, that can be + or - 80 higher or lower, and < 80 away. Now here is the problem, I don`t know how to code it in Xcode. My code so far :

         SKTexture * BlockTexture1 = [SKTexture textureWithImageNamed:@"Block"];
    BlockTexture1.filteringMode = SKTextureFilteringNearest;
    SKTexture * BlockTexture2 = [SKTexture textureWithImageNamed:@"Block"];
    BlockTexture2.filteringMode = SKTextureFilteringNearest;

    SKSpriteNode * Block1 = [SKSpriteNode spriteNodeWithTexture:BlockTexture1];
    [Block1 setScale:1];
    Block1.position = CGPointMake( 100 , 150 );
    Block1.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:Block1.size];
    Block1.physicsBody.dynamic = NO;
    Block1.physicsBody.usesPreciseCollisionDetection = YES;
    Block1.zPosition = 3;
    [self addChild:Block1];

    SKSpriteNode * Block2 = [SKSpriteNode spriteNodeWithTexture:BlockTexture2];
    [Block2 setScale:1];
    Block2.position = CGPointMake( **Block1 + or - 80, Block 1 < 80** );
    Block2.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:Block2.size];
    Block2.physicsBody.dynamic = NO;
    Block2.physicsBody.usesPreciseCollisionDetection = YES;
    Block2.zPosition = 3;
    [self addChild:Block2];

Solution

  • To get your started, something like this perhaps:

    int block1x = 100;
    int block1y = 150;
    
    Block1.position = CGPointMake(block1x, block1y);
    
    int block2x = 0;
    int block2y = 0;
    
    int r1 = arc4random() % 2; // produces random numbers between 0 and 1
    if(r1 == 0)
       block2x = block1x + 80;
    if(r1 == 1)
       block2x = block1x - 80;
    
    int r2 = arc4random() % 2;
    if(r2 == 0)
       block2y = block1y + 80;
    if(r2 == 1)
       block2y = block1y - 80;
    
    Block2.position = CGPointMake(block2x, block2y);