如何对加速度计进行编码以使其具有固定的 x 位置
How to code the accelerometer to have a fixed x position
我有一艘根据重力方向移动的船,重力方向由加速度计改变,但我希望它只沿着屏幕的宽度移动(我已经知道该怎么做),但我知道不知道如何将其保持在固定的水平线上。这是我的代码
class GameScene: SKScene {
var manager = CMMotionManager()
var ship = SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let shipTexture = SKTexture(imageNamed: "EvadersShipVert2.png")
ship = SKSpriteNode(texture: shipTexture)
ship.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - 250)
ship.size = CGSize(width: 90, height: 115)
shipTexture.filteringMode = SKTextureFilteringMode.Nearest
ship.zPosition = 2
ship.physicsBody = SKPhysicsBody(texture: shipTexture, size: CGSize(width: 90, height: 115))
ship.physicsBody?.dynamic = true
self.addChild(ship)
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
(data, error) in
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!), CGFloat((data?.acceleration.y)!))
}
}
提前致谢!
替换
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!), CGFloat((data?.acceleration.y)!))
有
self.physicsWorld.gravity = CGVectorMake(0.0, CGFloat((data?.acceleration.y)!)
所以你不会影响 x 位置
我有一艘根据重力方向移动的船,重力方向由加速度计改变,但我希望它只沿着屏幕的宽度移动(我已经知道该怎么做),但我知道不知道如何将其保持在固定的水平线上。这是我的代码
class GameScene: SKScene {
var manager = CMMotionManager()
var ship = SKSpriteNode()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let shipTexture = SKTexture(imageNamed: "EvadersShipVert2.png")
ship = SKSpriteNode(texture: shipTexture)
ship.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame) - 250)
ship.size = CGSize(width: 90, height: 115)
shipTexture.filteringMode = SKTextureFilteringMode.Nearest
ship.zPosition = 2
ship.physicsBody = SKPhysicsBody(texture: shipTexture, size: CGSize(width: 90, height: 115))
ship.physicsBody?.dynamic = true
self.addChild(ship)
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) {
(data, error) in
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!), CGFloat((data?.acceleration.y)!))
}
}
提前致谢!
替换
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)!), CGFloat((data?.acceleration.y)!))
有
self.physicsWorld.gravity = CGVectorMake(0.0, CGFloat((data?.acceleration.y)!)
所以你不会影响 x 位置