我一直在绞尽脑汁,到处搜索,试图找出如何在屏幕上生成一个随机位置来生成一个圆圈。我希望这里有人可以帮助我,因为我完全被难住了。基本上,我试图创建一个形状,当用户触摸时,该形状总是在屏幕上的随机位置生成。
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenHeight = screenSize.height
let screenWidth = screenSize.width
let currentBall = SKShapeNode(circleOfRadius: 100)
currentBall.position = CGPointMake(CGFloat(arc4random_uniform(UInt32(Float(screenWidth)))), CGFloat(arc4random_uniform(UInt32(Float(screenHeight)))))
self.removeAllChildren()
self.addChild(currentBall)
}
如果你们都需要更多我的代码,我真的没有了。但感谢您提供的任何帮助! (重申一下,这段代码是有效的......但是大多数生成的球似乎都是在屏幕外生成的)
最佳答案
问题在于您的场景大于屏幕边界
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)
关于ios - 在屏幕上的随机位置生成一个圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39302346/