Reputation: 66
I am trying to position my 1 nodes at random between 3 Points. Lets say these Positions are :
1: CGPoint(x: CGRectGetMidX(self.frame) - 123.5 , y: CGRectGetMidY(self.frame) * 2.5)
2: CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame) * 2.5)
3: CGPoint(x: CGRectGetMidX(self.frame) + 123.5 , y: CGRectGetMidY(self.frame) * 2.5)
My code:
let arabaHareketi = SKAction.moveByX(0, y: -self.frame.size.height * 2, duration: 2.5)
let turuncuYapılışı = SKTexture(imageNamed: "turuncu")
let turuncu = SKSpriteNode(texture: turuncuYapılışı)
turuncu.size = CGSizeMake(104, 204)
turuncu.position = CGPoint(x: CGRectGetMidX(self.frame) - 123.5 + pipeOffSet , y: CGRectGetMidY(self.frame) * 2.5)
turuncu.physicsBody = SKPhysicsBody(rectangleOfSize: turuncu.size)
turuncu.physicsBody?.dynamic = false
turuncu.runAction(arabaHareketi)
turuncu.zPosition = 21
self.addChild(turuncu)
Upvotes: 1
Views: 194
Reputation: 1205
You can use arc4random()
to get a random number. Get the remainder by running % 3
on it. Then use an if statement system to check the remainders (which in this case will be 0, 1, or 2). Here's some code for this:
let index = arc4random() % 3;
if index == 0 {
turuncu.position = CGPoint(x: CGRectGetMidX(self.frame) - 123.5 , y: CGRectGetMidY(self.frame) * 2.5)
} else if index == 1 {
turuncu.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame) * 2.5)
} else {
turuncu.position = CGPoint(x: CGRectGetMidX(self.frame) + 123.5 , y: CGRectGetMidY(self.frame) * 2.5)
}
If you want to add additional possibilities, take the middle else if
statement, and continue to chain it. Something like this:
if condition1 {
} else if condition2 {
} else if condition3 {
...
} else if conditionN {
} else {
}
Make sure put in a higher number for the remainder operator if you choose to have more conditions.
Upvotes: 2