Shake

dice

//
//  ViewController.swift
//  Shake
//
//  Created by Kyoung Shin Park on 12/7/15.
//  Copyright © 2015 Kyoung Shin Park. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var diceLabel: UILabel!

@IBOutlet weak var diceNumberTextfield: UITextField!

@IBOutlet weak var diceImageView: UIImageView!

func toggleAnimation() {
if diceImageView.isAnimating() {
diceImageView.stopAnimating()
} else {
diceImageView.startAnimating()
}
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
diceImageView.image = UIImage(named: “dice0”)!
diceImageView.animationImages = [
UIImage(named: “dice0”)!,
UIImage(named: “dice1”)!,
UIImage(named: “dice2”)!,
UIImage(named: “dice3”)!,
UIImage(named: “dice4”)!,
UIImage(named: “dice5”)!,
UIImage(named: “dice6”)!
]
diceImageView.animationDuration = 5
diceImageView.animationRepeatCount = 0
//diceImageView.startAnimating()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// http://www.ioscreator.com/tutorials/detect-shake-gesture-ios8-swift
override func canBecomeFirstResponder() -> Bool {
return true
}

// UIEvent? must be used. It has been changed since Swift 2.0
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
diceImageView.startAnimating()
diceLabel.text = “Shaking!”
}

// UIEvent? must be used. It has been changed since Swift 2.0
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
let range = (1, 6)
let num = arc4random_uniform(UInt32(range.1 – range.0) + 1) + UInt32(range.0)
self.diceNumberTextfield.text = String(num)
let imageName = “dice\(num)”
diceImageView.image = UIImage(named: imageName)!

diceImageView.stopAnimating()
diceLabel.text = “Re-shake your device to roll a dice”
}
}
}

SpriteKit

//
//  GameScene.swift
//  SimpleSprite
//
//  Created by Park on 12/5/16.
//  Copyright (c) 2016 Park. All rights reserved.
//
import CoreMotion // motion
import SpriteKit

class GameScene: SKScene {
var motionManager = CMMotionManager() // motion
var dustSprite = SKSpriteNode(imageNamed:”CAHUFOZY”) // sprite moved by motion
var destX: CGFloat = 0.0
var destY: CGFloat = 0.0
var positionLabel = SKLabelNode(fontNamed: “Courier”)

func setupHud() {
positionLabel.name = “dustSprite Position”
positionLabel.fontSize = 35
positionLabel.text = String(format: “x: %.1f%% y: %.1f%%”,destX, destY)
positionLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMaxY(self.frame) – 50)
self.addChild(positionLabel)
}

override func didMoveToView(view: SKView) {
motionManager.startAccelerometerUpdates() // motion

dustSprite.xScale = 1.5
dustSprite.yScale = 1.5
dustSprite.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
dustSprite.runAction(SKAction.repeatActionForever(action))
self.addChild(dustSprite)

if motionManager.accelerometerAvailable == true {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
data, error in
let currentX = self.dustSprite.position.x
if data!.acceleration.x < 0 {
self.destX = currentX + CGFloat(data!.acceleration.x * 100)
}
else if data!.acceleration.x > 0 {
self.destX = currentX + CGFloat(data!.acceleration.x * 100)
}
let currentY = self.dustSprite.position.y
if data!.acceleration.y < 0 {
self.destY = currentY + CGFloat(data!.acceleration.y * 100)
}
else if data!.acceleration.y > 0 {
self.destY = currentY + CGFloat(data!.acceleration.y * 100)
}
})
}

/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:”Chalkduster”)
myLabel.text = “Hello, Sprite!”
myLabel.fontSize = 45
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
self.addChild(myLabel)

setupHud() // hud
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */

for touch in touches {
let location = touch.locationInNode(self)

let sprite = SKSpriteNode(imageNamed:”Spaceship”)

sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.position = location

let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)

sprite.runAction(SKAction.repeatActionForever(action))

self.addChild(sprite)
}
}

override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */

positionLabel.text = String(format: “x: %.1f%% y: %.1f%%”,destX, destY)

let maxX = CGRectGetMaxX(self.frame) – dustSprite.size.width
let maxY = CGRectGetMaxY(self.frame) – dustSprite.size.height
let minX = CGRectGetMinX(self.frame) + dustSprite.size.width
let minY = CGRectGetMinY(self.frame) + dustSprite.size.height
if destX > maxX {
destX = maxX
}
else if destX < minX {
destX = minX
}
if destY > maxY {
destY = maxY
}
else if destY < minY {
destY = minY
}

let action = SKAction.moveTo(CGPoint(x: destX, y: destY), duration: 1)
self.dustSprite.runAction(action)
}
}

Accelerometer & Gyro

//
//  ViewController.swift
//  Accelometer
//
//  Created by Kyoung Shin Park on 12/7/15.
//  Copyright © 2015 Kyoung Shin Park. All rights reserved.
//

import UIKit
import CoreMotion

class ViewController: UIViewController {
@IBOutlet weak var accelerometerExistedLabel: UILabel!
@IBOutlet weak var accelerometerActiveLabel: UILabel!
@IBOutlet weak var xValue: UITextField!
@IBOutlet weak var yValue: UITextField!
@IBOutlet weak var zValue: UITextField!

@IBOutlet weak var gyroExistedLabel: UILabel!
@IBOutlet weak var gyroActiveLabel: UILabel!
@IBOutlet weak var xGyro: UITextField!
@IBOutlet weak var yGyro: UITextField!
@IBOutlet weak var zGyro: UITextField!

var motionManager = CMMotionManager() // must be created here so that it exists for the whole app run-time

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

if motionManager.accelerometerAvailable {
accelerometerExistedLabel.text = “Accelerometer avaialble”
if motionManager.accelerometerActive == false {
motionManager.accelerometerUpdateInterval = 1.0 / 10.0 // 10 updates per second
let accelQueue = NSOperationQueue()
motionManager.startAccelerometerUpdatesToQueue(accelQueue) {
(data, error) in
if error != nil {
print(“\(error)”)
}
else {
self.setAccelData(data!)
}
}
}
else {
accelerometerActiveLabel.text = “Accelerometer is already active”
}
}
else {
accelerometerExistedLabel.text = “Accelerometer is not avaialble”
}

if motionManager.gyroAvailable {
gyroExistedLabel.text = “Gyro avaialble”
if motionManager.gyroActive == false {
motionManager.gyroUpdateInterval = 0.2 // 5 updates per sec

let gyroQueue = NSOperationQueue()

// http://stackoverflow.com/questions/24233191/how-do-i-correctly-pass-a-block-handler-into-this-function-in-swift
motionManager.startGyroUpdatesToQueue(gyroQueue) {
(data, error) in
if error != nil {
print(“\(error)”)
}
else {
self.setGyroscopeData(data!)
}
}
}
else {
gyroActiveLabel.text = “Gyroscope is already active”
}
}
else {
gyroExistedLabel.text = “Gyroscope is not avaialble”
}
}

func setAccelData(data: CMAccelerometerData) {
// http://blog.digitalneurosurgeon.com/?p=2697
// Although retrieving gyroscope data in different thread using newly created NSOpeartionQueue, updating UI should be done in main thread

let x = data.acceleration.x
let y = data.acceleration.y
let z = data.acceleration.z
//                var angle = atan2(y, x)
dispatch_sync(dispatch_get_main_queue()) {
self.accelerometerActiveLabel.text = “Accelerometer is active”

self.xValue?.text = String(format: “%0.2f”, x)
self.yValue?.text = String(format: “%0.2f”, y)
self.zValue?.text = String(format: “%0.2f”, z)
}
}

func setGyroscopeData(data: CMGyroData) {
// http://blog.digitalneurosurgeon.com/?p=2697
// Although retrieving gyroscope data in different thread using newly created NSOpeartionQueue, updating UI should be done in main thread
let x: Double = data.rotationRate.x
let y: Double = data.rotationRate.y
let z: Double = data.rotationRate.z

dispatch_sync(dispatch_get_main_queue()) {
self.gyroActiveLabel.text = “Gyroscope is active”

self.xGyro?.text = String(format: “%0.2f”, x)
self.yGyro?.text = String(format: “%0.2f”, y)
self.zGyro?.text = String(format: “%0.2f”, z)
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}