Burundanga
Burundanga

Reputation: 668

How to "glue" one node to another in SpriteKit?

Let's say I have a table node. This node is moving horizontally through the scene like this

func newPlace() {
table.position = CGPointMake(self.size.width + 100, CGRectGetMidY (self.frame)
}
var moveTable = SKAction.moveToX(-50, duration: 1)
var placeTable = SKAction.runBlock(newPlace)
var moveAlong = SKAction.moveToX(-100, duration: 2)
var seq = SKAction.sequence([placeTable, moveAlong])
var repeatTable = SKAction.repeatActionForever(seq)
var sequenceTable = SKAction.sequence([ moveTable, placeTable, moveAlong, seq, repeatTable])
table.runAction(sequenceTable)

First of all, is there any other easier or shorter way to perform that type of endless spawning? But my main question is how to place a fruit on that table? It should be on random spot of a table, but not in the air. So I need somehow to glue that fruit to the table and make it's spot on a table random every time table appears. How to do that?

Upvotes: 1

Views: 133

Answers (1)

ABakerSmith
ABakerSmith

Reputation: 22939

To 'glue' the fruit to the table you should use the addChild method from SKNode. For example:

table.addChild(fruit)

As for the random positioning, you'll firstly need to generate a random CGFloat within an interval:

func randomCGFloat(#min: CGFloat, max: CGFloat) -> CGFloat {
    let p = CGFloat(arc4random()) / CGFloat(UInt32.max)
    return (max - min) * p + min
}

For Swift 2 the function would be

func randomCGFloat(min min: CGFloat, max: CGFloat) -> CGFloat {
    // ... 
}

You can then use this to randomly position the fruit. It's important to bear in mind that the anchor point of an SKSpriteNode is (0.5, 0.5) by default and so the origin is in the middle of the table sprite.

For a random position on the x-axis, assuming the anchorPoint of both the table and fruit is (0.5, 0.5), you could do:

let minX = (-table.size.width + fruit.size.width) / 2
let maxX = ( table.size.width - fruit.size.width) / 2
fruit.position.x = randomCGFloat(min: minX, max: maxX)

Upvotes: 2

Related Questions