ARKIT

SpriteKit(5) - 交互(Node重力感应)

2017-07-29  本文已影响56人  li_礼光
import SpriteKit
import GameplayKit
import CoreMotion

class GameGravity: SKScene {
    
    var motionManager : CMMotionManager = CMMotionManager()
    var node : SKSpriteNode!
    
    override func didMove(to view: SKView) {
        //布置场景
        self.size = UIScreen.main.bounds.size
        node = SKSpriteNode()
        node.name = "gravity"
        node.size = CGSize(width: 100, height: 100)
        node.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
        node.color = UIColor.red
        self.addChild(node)

        print(motionManager)
        if motionManager.isAccelerometerAvailable {
            print("支持重力")
        }

        //重力感应操作
        motionManager.startAccelerometerUpdates()
        self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame)
        self.node.physicsBody = SKPhysicsBody(rectangleOf: self.node.frame.size)
        self.node.physicsBody?.isDynamic = true             //能承受碰撞和其他外力作用
        self.node.physicsBody?.affectedByGravity = false    //不受重力影响
        self.node.physicsBody?.mass = 0.2                   //给node任意质量,显得更加自然
    }
    
    
    override func update(_ currentTime: TimeInterval) {
        guard let data : CMAccelerometerData = self.motionManager.accelerometerData else {
            print("data == nil")
            return
        }
        let value  : Double = data.acceleration.y
        print(data)
        if fabs(value) > 0.2 {
            let fvector = CGVector(dx: 80.0 * CGFloat(value), dy: 0)
            self.node.physicsBody?.applyForce(fvector)
        }
    }  
}
重力感应方向

因为这里是横屏操作,所以考虑好重力感应的x,y,z和node位置

上一篇下一篇

猜你喜欢

热点阅读