Spawning a circle in a random spot on screen

前端 未结 3 552
闹比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:33

    First: Determine the area that will be valid. It might not be the frame of the superview because perhaps the ball (let's call it ballView) might be cut off. The area will likely be (in pseudocode):

    CGSize( Width of the superview - width of ballView , Height of the superview - height of ballView)
    

    Once you have a view of that size, just place it on screen with the origin 0, 0.

    Secondly: Now you have a range of valid coordinates. Just use a random function (like the one you are using) to select one of them.

    Create a swift file with the following:

    extension Int
    {
        static func random(range: Range) -> Int
        {
            var offset = 0
    
            if range.startIndex < 0   // allow negative ranges
            {
                offset = abs(range.startIndex)
            }
    
            let mini = UInt32(range.startIndex + offset)
            let maxi = UInt32(range.endIndex   + offset)
    
            return Int(mini + arc4random_uniform(maxi - mini)) - offset
        }
    }
    

    And now you can specify a random number as follows:

    Int.random(1...1000) //generate a random number integer somewhere from 1 to 1000.
    

    You can generate the values for the x and y coordinates now using this function.

提交回复
热议问题