Sprite Kit random positions

↘锁芯ラ 提交于 2019-12-13 00:48:46

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/32399010/sprite-kit-random-positions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!