我是spritekit的新手,并试图开发一款带有Acceleromotion限制SKSpritNode走出屏幕的游戏。当我设置Player.physicsBody!动态=真,但相同的代码不工作时设置此属性为"假"。请告诉我哪里做错了下面是代码:
import SpriteKit
import CoreMotion
class EndScene : SKScene,SKPhysicsContactDelegate {
let kShipName = "ship"
var Player = SKSpriteNode(imageNamed: "Airplane")
let motionManager: CMMotionManager = CMMotionManager()
override func didMoveToView(view: SKView) {
physicsWorld.contactDelegate = self
physicsBody = SKPhysicsBody(edgeLoopFromRect: frame)
Player.position = CGPointMake(self.size.width / 2, self.size.height / 5)
Player.physicsBody = SKPhysicsBody(rectangleOfSize: Player.frame.size)
Player.physicsBody?.affectedByGravity = false
Player.physicsBody?.categoryBitMask = PhysicsCategory.Player
Player.physicsBody?.contactTestBitMask = PhysicsCategory.Enemy
Player.physicsBody?.dynamic = false
Player.physicsBody!.mass = 0.02
self.addChild(Player)
Player.setScale(0.4)
Player.name = kShipName
motionManager.startAccelerometerUpdates()
}
func processUserMotionForUpdate(currentTime: CFTimeInterval) {
// 1
if let ship = childNodeWithName(kShipName) as? SKSpriteNode {
// 2
if let data = motionManager.accelerometerData {
// 3
if fabs(data.acceleration.x) > 0.2 {
// 4 How do you move the ship?
Player.physicsBody!.applyForce(CGVectorMake(30.0 * CGFloat(data.acceleration.x), 0))
}
}
}
}
override func update(currentTime: CFTimeInterval) {
processUserMotionForUpdate(currentTime)
}
}
如果你的精灵不是动态的,你就不能对它应用力/脉冲。
根据苹果关于SKPhysicsBodies动态属性的文档
"默认值为YES。如果该值为NO,则物理体忽略施加于其上的所有力和脉冲。此属性在基于边缘的物体上被忽略;它们是自动静态的。"
正如其他人指出的,你也应该清理你的厄运金字塔
func processUserMotionForUpdate(currentTime: CFTimeInterval) {
// 1
guard let ship = childNodeWithName(kShipName) as? SKSpriteNode else { return }
// 2
guard let data = motionManager.accelerometerData else { return }
// 3
guard fabs(data.acceleration.x) > 0.2 else { return }
// 4 How do you move the ship?
Player.physicsBody!.applyForce(CGVectorMake(30.0 * CGFloat(data.acceleration.x), 0))
}
也试着遵循swift准则,你的播放器属性应该以一个小写字母
开头let player = SKSpriteNode(imageNamed: "Airplane")