我正在尝试使用倾斜屏幕来移动我的播放器的选项。因此,我遵循Ray Wenderlich和他的太空入侵者教程的指示。我似乎无法弄清楚为什么在倾斜屏幕时我的玩家没有从左向右移动。
请看看它可以帮助我。
import SpriteKit
import CoreMotion
enum BodyType: UInt32 {
case player = 2
case enemy = 3
}
let motionManager = CMMotionManager()
class GameScene: SKScene, SKPhysicsContactDelegate {
let points = SKLabelNode(text: "0")
let gamePlayerSize = CGSize(width: 30, height: 16)
let gamePlayerName = "gameplayer"
override func didMove(to view: SKView) {
//SET UP FRAME
physicsBody = SKPhysicsBody(edgeLoopFrom: frame)
//SETTING UP Player
func setupPlayer() {
// 1
let player = makePlayer()
// 2
player.position = CGPoint(x: 240, y: 28)
addChild(player)
}
func makePlayer() -> SKNode {
let player = SKSpriteNode(imageNamed: "block")
player.name = gamePlayerName
// 1
player.physicsBody = SKPhysicsBody(rectangleOf: player.frame.size)
// 2
player.physicsBody!.isDynamic = true
// 3
player.physicsBody!.affectedByGravity = false
// 4
player.physicsBody!.mass = 0.02
return player
}
setupPlayer()
motionManager.startAccelerometerUpdates()
//score label
let points = SKLabelNode(text: "0")
points.position = CGPoint(x: 280, y: 510)
points.fontColor = UIColor.black
points.fontSize = 50
addChild(points)
// setting border around game
let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
borderBody.friction = 0
self.physicsBody = borderBody
//ENEMY SETTINGS START
//repeat enemy spawning
run(SKAction.repeatForever(
SKAction.sequence([
SKAction.run(spawnEnemy),
SKAction.wait(forDuration: 1.0)])))
}
//Enemy settings
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
//spawn enemies
func spawnEnemy() {
// 2
let enemy = SKSpriteNode(imageNamed: "ball")
// 3
enemy.name = "enemy"
// 4
enemy.position = CGPoint(x: frame.size.width * random(min: 0, max: 1), y: frame.size.height + enemy.size.height/2)
// 5
addChild(enemy)
enemy.run(
SKAction.moveBy(x: 0.0 , y: -size.height - enemy.size.height,
duration: TimeInterval(random(min: 1, max: 2))))
//ENEMY SETTINGS END
func processUserMotion(forUpdate currentTime: CFTimeInterval) {
// 1
if let player = childNode(withName: gamePlayerName) 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(CGVector(dx: 40 * CGFloat(data.acceleration.x), dy: 0))
}
}
}
}
func update(_ currentTime: TimeInterval) {
processUserMotion(forUpdate: currentTime)
}
} }
您是否偶然地嵌套了方法?查看您的代码似乎是如此。
您是否检查了运动代码是否被调用?
这样的事情应该起作用
class GameScene: SKScene {
let motionManager = CMMotionManager()
override func didMove(to view: SKView) {
// setup player etc
motionManager.startAccelerometerUpdates()
}
func update(_ currentTime: TimeInterval) {
processUserMotion(forUpdate: currentTime)
}
}
也作为提示,当使用物理主体而不是强制解开它们时,我会使用optionals(?)(!)。如果它在某一时刻变成零您将在武力解开时崩溃。
例如
player.physicsBody?.affectedByGravity = false
希望这有帮助