我正在研究一個「太空入侵者」遊戲,我已經實現了CMMotionManager來傾斜我的英雄船隻(遊戲只在風景中運行),但由於某種原因,我的船將移出該視圖儘管讓一個SKNode離開視圖
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
應該通過使物理邊緣阻止這一點。任何想法爲什麼?
import SpriteKit
import CoreMotion
class GameScene: SKScene,SKPhysicsContactDelegate{
let collisionBulletCategory: UInt32 = 0x1 << 0
let collisionHeroCategory: UInt32 = 0x1 << 1
let background = SKSpriteNode(imageNamed: "background")
let heroShip = SKSpriteNode(imageNamed: "heroShip")
let enemyShip = SKSpriteNode(imageNamed: "enemyShip")
let MotionManager = CMMotionManager()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
background.position = CGPointMake(CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
heroShip.anchorPoint = CGPointMake(1.0, 0.5)
heroShip.physicsBody?.mass = 0.02
heroShip.physicsBody?.dynamic = true
heroShip.physicsBody = SKPhysicsBody(rectangleOfSize: heroShip.size)
heroShip.physicsBody?.affectedByGravity = false
heroShip.physicsBody?.categoryBitMask = collisionHeroCategory
heroShip.physicsBody?.contactTestBitMask = collisionBulletCategory
heroShip.physicsBody?.collisionBitMask = 0x0
heroShip.position = CGPointMake(self.size.width/6.0, self.size.height/2.0)
enemyShip.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
enemyShip.zPosition = 1.0
self.heroShip.zPosition = 1.0
self.addChild(enemyShip)
self.addChild(background)
self.addChild(heroShip)
if MotionManager.accelerometerAvailable{
MotionManager.startAccelerometerUpdates()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let bullet = SKSpriteNode(imageNamed: "bullet")
bullet.position = CGPointMake(heroShip.position.x, heroShip.position.y)
bullet.zPosition = 1.0
// Add physics body for collision detection
bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.frame.size)
bullet.physicsBody?.dynamic = true
bullet.physicsBody?.affectedByGravity = false
bullet.physicsBody?.categoryBitMask = collisionBulletCategory
bullet.physicsBody?.contactTestBitMask = collisionHeroCategory
bullet.physicsBody?.collisionBitMask = 0x0;
let action = SKAction.moveToX(CGRectGetMaxX(self.frame) + bullet.size.width, duration: 0.75)
self.addChild(bullet)
bullet.runAction(action, completion: {
bullet.removeAllActions()
bullet.removeFromParent()
})
}
func didBeginContact(contact: SKPhysicsContact) {
}
override func update(currentTime: CFTimeInterval) {
let data = MotionManager.accelerometerData
if data?.acceleration.x == nil{
print("nil")
}
else if fabs((data?.acceleration.x)!) > 0.2 {
self.heroShip.physicsBody?.applyForce(CGVectorMake(0.0, CGFloat(50 * (data?.acceleration.x)!)))
}
}
}
這是正確的,我剛結束了0x0和沒有一個sceneCategory UInt32的設置呢。感謝您的幫助 –