//
// ViewController.swift
// Ball
//
// Created by Romance on 17/5/10.
// Copyright (c) 2017年 jschrjkj. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
var ball:UIImageView!
var speedx:UIAccelerationValue=0
var speedy:UIAccelerationValue=0
var motionmanger=CMMotionManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ball=UIImageView(image: UIImage(named: "ball"))
ball.frame=CGRectMake(0, 0, 50, 50)
ball.center=self.view.center
self.view.addSubview(ball)
motionmanger.accelerometerUpdateInterval=1/60
if(motionmanger.accelerometerAvailable)
{
var queue = NSOperationQueue.currentQueue()
motionmanger.startAccelerometerUpdatesToQueue(queue, withHandler: { (AccelerometerData:CMAccelerometerData!, error:NSError!) in
self.speedx+=AccelerometerData.acceleration.x
self.speedy+=AccelerometerData.acceleration.y
var posx=self.ball.center.x+CGFloat(self.speedx)
var posy=self.ball.center.y+CGFloat(self.speedy)
if posx<0{
posx=0
self.speedx *= -0.4
}
else if posx>self.view.bounds.size.width{
posx=self.view.bounds.size.width
self.speedx *= -0.4
}
if posy<0{
posy=0
}
else if posy>self.view.bounds.size.height{
posy=self.view.bounds.size.height
self.speedx *= -1.5
}
self.ball.center=CGPointMake(posx, posy)
})
}
else
{
println("Error");
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}