【发布时间】:2016-01-19 21:57:00
【问题描述】:
我正在开发一款“太空侵略者”游戏,我已经实现了 CMMotionManager 来倾斜移动我的 heroShip(游戏只在横向运行),但由于某种原因,即使我的船会移出视图
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)!)))
}
}
}
【问题讨论】:
标签: ios swift sprite-kit