デバイスの傾きをCMMotionManagerで取得すれば、水準器みたいなことができる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// GameScene.swift import SpriteKit import GameplayKit import CoreMotion class GameScene: SKScene { let redBallCategory:UInt32 = 0b0001 let circleCategory:UInt32 = 0b0001 private let motionManager = CMMotionManager() override func didMove(to view: SKView) { let ballRadius: CGFloat = 20 let redBall = SKShapeNode(circleOfRadius: ballRadius) redBall.fillColor = .red redBall.position = CGPoint(x: 160, y: 320) redBall.physicsBody = SKPhysicsBody(circleOfRadius: ballRadius) let circle = SKShapeNode(circleOfRadius: 150.0) circle.position = CGPoint(x:160, y: 320) circle.strokeColor = .white circle.physicsBody = SKPhysicsBody(edgeChainFrom: circle.path!) circle.physicsBody?.restitution = 0.75 redBall.physicsBody?.collisionBitMask = 0b0001 circle.physicsBody?.categoryBitMask = 0b0001 self.addChild(redBall) self.addChild(circle) redBall.physicsBody?.categoryBitMask = redBallCategory circle.physicsBody?.categoryBitMask = circleCategory } override func sceneDidLoad() { super.sceneDidLoad() guard motionManager.isDeviceMotionAvailable else { return } motionManager.deviceMotionUpdateInterval = 0.1 // 0.1 Sec motionManager.startDeviceMotionUpdates(using: .xMagneticNorthZVertical, to: OperationQueue.current!, withHandler: { [weak self] (motion, error) in guard let motion = motion, error == nil else { return } self?.physicsWorld.gravity = CGVector(dx:motion.attitude.roll * 5.0, dy:-motion.attitude.pitch * 5.0) }) } } |