我正在尝试获取设备运动数据并改变重力方向,这样当我倾斜我的 iPhone 时,球就会在倾斜方向上移动。在本教程中,方法是在节点上获取加速度数据和 applyForce。但是,我想通过改变重力方向来实现这个目标(无论我如何倾斜手机,重力总是沿着真实的物理重力方向)。
这是我的代码:
import SpriteKit
import CoreMotion
class GameScene: SKScene {
let ballName = "redBall"
var gravityDirection = CGVectorMake(0,-9.8)
let motionManager = CMMotionManager()
let motion = CMDeviceMotion()
func addBall(){
//Create the ball
var ball = SKShapeNode()
var path = CGPathCreateMutable()
CGPathAddArc(path, nil, 0, 0, 45, 0, CGFloat(M_PI * 2), true)
CGPathCloseSubpath(path)
ball.name = ballName
ball.path = path
ball.lineWidth = 2.0
ball.fillColor = SKColor(red: 0.95, green: 0.2, blue: 0.2, alpha: 0.9)
ball.position = CGPoint(x:size.width/2, y: size.height)
//Set the ball's physcial properties
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.frame.width/2)
ball.physicsBody!.dynamic = true
ball.physicsBody!.mass = 0.1
ball.physicsBody!.friction = 0.2
ball.physicsBody!.restitution = 0.9
ball.physicsBody!.affectedByGravity = true
self.addChild(ball)
}
func gravityUpdated(){
let vector = CGVectorMake(CGFloat(motion.gravity.x), CGFloat(motion.gravity.y))
self.physicsWorld.gravity = vector
}
override func didMoveToView(view: SKView) {
physicsBody = SKPhysicsBody(edgeLoopFromRect: view.frame)
self.physicsWorld.gravity = gravityDirection
motionManager.startDeviceMotionUpdates()
addBall()
}
override func update(currentTime: CFTimeInterval) {
gravityUpdated()
}
}
在上面的代码中,我使用 CMDeviceMotion 来获取重力数据,并将重力值赋予physicsWorld.gravity。该应用程序在我运行时总是崩溃。
Xcode 表示gravityUpdate() 函数中存在错误,但我找不到。希望有人能帮我解决这个问题。或者给我一个更好的方法来模拟重力。谢谢!