2017-02-14 78 views
0

我試圖使用內置的加速度計在x軸上移動播放器,但出了點問題。當我在iPhone上模擬應用程序時,節點會繼續向各個方向移動,並且只有在關閉應用程序並再次啓動後,節點纔會從左向右移動,這正是我想要的。所以它的作品,但只有在關閉並再次打開應用程序後。代碼奇怪的加速度計行爲(CoreMotion)

部分:

import Foundation 
import SpriteKit 
import CoreMotion 

class Gameplay : SKScene{ 

    private var player : Player? 

    var motionManager = CMMotionManager() 

    override func update(_ currentTime: TimeInterval) { 
     self.player?.move() 
    } 

    func initializeGame(){ 
     player = childNode(withName: "player") as? Player! 
     player?.initPlayer() 
    } 

    override func didMove(to view: SKView) { 

     initializeGame() 

     motionManager.startAccelerometerUpdates() 
     motionManager.accelerometerUpdateInterval = 0.1 
     motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data , _) in 
      if let accelerometerData = data{ 
       print("x: \(accelerometerData.acceleration.x)") 
       print("y: \(accelerometerData.acceleration.y)") 
       self.physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.x*10, dy: 0) //only x axis? 
      } else { 
       print("NOPE") 
      } 

     } 
    } 

Player.swift:

import Foundation 
import SpriteKit 

class Player : SKSpriteNode{ 

    func initPlayer(){ 
     name = "Player" 

     physicsBody?.affectedByGravity = true 
     physicsBody?.isDynamic = true 

    } 

    func move(){ //boundaries 
     if position.x >= 315{ 
      position.x = 315 
     } else if position.x <= -315{ 
      position.x = -315 
     } 
    } 

    func shoot(){ 
     //... 
    } 

} 

回答

1

而是改變你的場景的嚴重性,試圖直接移動玩家。如果你調整重力,它也會搞亂你所有的其他物理機構。因此,無論是使用SKAction還是通過對其施加武力來移動玩家。

player?.physicsBody?.applyForce(CGVector(dx: 30 * CGFloat(accelerometerData.acceleration.x), dy: 0)) 

我也建議你不要使用處理程序的運動更新,我從來沒有得到準確的結果使用它。

所以刪除此代碼塊

motionManager.startAccelerometerUpdates(to: OperationQueue.current!) { (data , _) in 
     if let accelerometerData = data{ 
      print("x: \(accelerometerData.acceleration.x)") 
      print("y: \(accelerometerData.acceleration.y)") 
      self.physicsWorld.gravity = CGVector(dx: accelerometerData.acceleration.x*10, dy: 0) //only x axis? 
     } else { 
      print("NOPE") 
     } 

    } 

,而是去到場景的更新方法,並從那裏獲取的運動數據。

override func update(_ currentTime: TimeInterval) { 

    if let accelerometerData = motionManager.accelerometerData { 
     player?.physicsBody?.applyForce(CGVector(dx: 30 * CGFloat(accelerometerData.acceleration.x), dy: 0)) 
    } 
    .... 
} 

這將使一切更順暢和響應。調整30以獲得所需的結果。

希望這會有所幫助