ios - 在屏幕上的随机位置生成一个圆圈

标签 ios swift random arc4random

我一直在绞尽脑汁,到处搜索,试图找出如何在屏幕上生成一个随机位置来生成一个圆圈。我希望这里有人可以帮助我,因为我完全被难住了。基本上,我试图创建一个形状,当用户触摸时,该形状总是在屏幕上的随机位置生成。

    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/

相关文章:

ios - gidsignin 与 swift 和 firebase : Checking if the user is a new or returning user

ios - 当不同的按钮通向同一个 ViewController 时,我如何快速知道按下了哪个按钮?

IOS模拟器安装子版本

macos - 使用 Swift 获取已安装的卷列表?

ios - 快速捕获无效用户输入的异常

sql - MySQL:ORDER BY RAND() 的替代方案

ios - UIImage 未在 Xcode 6.3.1 Playground 中呈现

ios - UISplitViewController:在detailView中导航

c - 在 C 中生成随机数

css - 如果我想随机化颜色,但在随机化发生时使用 onload 方法制作了一组颜色,该怎么办?