Spawning a circle in a random spot on screen

前端 未结 3 531
闹比i
闹比i 2021-01-15 03:05

I\'ve been racking my brain and searching here and all over to try to find out how to generate a random position on screen to spawn a circle. I\'m hoping someone here can he

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-15 03:48

    The problem there is that you scene is bigger than your screen bounds

    let viewMidX = view!.bounds.midX
    let viewMidY = view!.bounds.midY
    print(viewMidX)
    print(viewMidY)
    
    let sceneHeight = view!.scene!.frame.height
    let sceneWidth = view!.scene!.frame.width
    print(sceneWidth)
    print(sceneHeight)
    
    let currentBall = SKShapeNode(circleOfRadius: 100)
    currentBall.fillColor = .green
    
    let x = view!.scene!.frame.midX - viewMidX + CGFloat(arc4random_uniform(UInt32(viewMidX*2)))
    let y = view!.scene!.frame.midY - viewMidY + CGFloat(arc4random_uniform(UInt32(viewMidY*2)))
    print(x)
    print(y)
    
    currentBall.position = CGPoint(x: x, y: y)
    view?.scene?.addChild(currentBall)
    
    self.removeAllChildren()
    self.addChild(currentBall)
    

提交回复
热议问题