Alec Norrie
Alec Norrie

Reputation: 113

Move a node based off of the randomized position of another node

I want to make it so my node (ball) always ends up resetting above my other node block1 based on where block 1 ends up. However, I could not think of any code that would help me do that. I was thinking of making a function saying something ball.position = block1 + 20 but I have no ideas of how to go about that. Thanks for any help!

Code:

func random() -> CGFloat {
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(min: CGFloat, max: CGFloat) -> CGFloat {
    return random() * (max - min) + min
}


func resetScene (){

     let ball = childNode(withName: BallCategoryName) as! SKSpriteNode
    ball.removeFromParent()

    ball.physicsBody?.velocity = CGVector( dx: 0, dy: 0 )
    ball.physicsBody?.collisionBitMask = BallCategory
    ball.physicsBody?.collisionBitMask = BorderCategory | PaddleCategory
    ball.zRotation = 0.0
    addChild(ball)
    let block1 = childNode(withName: Block1Name) as! SKSpriteNode
    block1.removeFromParent()
    let actualX = random(min:85, max: 300)
    block1.position = CGPoint(x: actualX, y: 190)
    addChild(block1)

//ball.position = CGPoint(x: , y: )

//This is the line i would like to change



    canRestart = false


}

Upvotes: 1

Views: 30

Answers (1)

Ron Myschuk
Ron Myschuk

Reputation: 6061

assuming you are just trying to set the Y position of your ball you can use

ball.position.y = block1.position.y + 20

or if you need to set the x and the y

ball.position = CGPoint(x: block1.position.x, y: block1.position.y + 20)

Upvotes: 1

Related Questions