0

I have a single UFO that is an UIImage and I simply want it to float around and come in and off at random locations like the asteroids in the game Asteroids. I put some rotation and grow in there temporarily. It would be nice if all of the animations were done randomly. Even if it was only random motion I'd be super happy. How do I implement arc4random()? After I accomplish that simple task I'd like to learn how to apply arc4random() to various behaviours in UIDynamics. Thanks in advance.

import UIKit

class ViewController: UIViewController {

@IBOutlet var ufo: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    UIView.animateWithDuration(5.5, delay: 0, options: .Repeat, animations: {
        let grow = CGAffineTransformMakeScale(2, 2)
        let angle = CGFloat( -30)
        let rotate = CGAffineTransformMakeRotation(angle)
        self.ufo.transform = CGAffineTransformConcat(grow, rotate)
        }, completion: nil)
}


}

1 Answers1

0

arc4random_uniform(n) will return a number from 0 to n. If you want this to return an Int then you can cast it as below:

var randomNumber = Int(arc4random_uniform(7))

Use this function to generate random numbers and then use those numbers in your animation.

For example, if you want your animation to have a random duration:

var duration = Double(arc4random_uniform(5)+1)
var x = CGFloat(arc4random_uniform(320))
var y = CGFloat(arc4random_uniform(960))
UIView.animateWithDuration(duration, delay: 0, options: .Repeat, animations: {
    let grow = CGAffineTransformMakeScale(2, 2)
    let angle = CGFloat( -30)
    let rotate = CGAffineTransformMakeRotation(angle)
    self.ufo.transform = CGAffineTransformConcat(grow, rotate)
    self.ufo.frame = CGRectMake(x,y,self.ufo.frame.size.width, self.ufo.frame.size.height)
    }, completion: nil)

The reason I have the arc4random_uniform(5)+1 is because the function is from 0 to n as I mentioned above, so 0 to 5 in this case but we do not want an animation with 0 duration so I added 1 to it to make the number 1 to 6.

chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • Thanks again. Just to be clear are you calling the declaration of the randomNumber variable a function? So how would I make my single UFO of UIImage randomly appear on and off the screen and with random speeds. As I was mentioning like Asteroids? Duration, grow, angle, rotate seem to be well documented but I can't find anything on how to make random x,y entrances or random acceleration. –  Mar 15 '15 at 05:15
  • I have updated my answer to do this. In order to achieve random "acceleration" using UIView animations instead of SpriteKit for actual physics you can randomize the duration as I did in the answer. – chrissukhram Mar 15 '15 at 20:20