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/30318002/

相关文章:

Python 错误 : "cannot find path specified"

ios - 我们可以快速为 2 个 Action 制作 1 个 UIButton 吗?

ios - 从其他 VC 加载 webview URL

ios - NSCFConstantString objectAtIndex : error in grouped table

iphone - 如何将坐标从英寸转换为像素?

ios - TTTAttributedLabel didSelectLink 未在 swift 4.0 中调用

xcode - 使用 Swift 的预期声明错误

javascript - javascript的随机实现在各种浏览器中的可信度如何?

c - 随机乱序内存泄漏

ios - 无效的代码签名权利。更改捆绑ID后