2016-07-09 4 views
-4

La dernière erreur:Présentation de l'accéléromètre? Correctif de code?

enter image description here

J'ai récemment travaillé sur une application avec un tutoriel et arriver à un point où je voudrais obliquer du tutoriel. Mais je n'ai presque aucune expérience avec SpriteKit donc je voudrais un peu d'aide en travaillant avec l'accéléromètre pour contrôler quelque chose sur l'application.

La partie où vous contrôlez le vaisseau spatial dans le jeu est ici:

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

     for touch: AnyObject in touches{ 

      let pointOfTouch = touch.locationInNode(self) 
      let previousPointOfTouch = touch.previousLocationInNode(self) 

      let amountDragged = pointOfTouch.x - previousPointOfTouch.x 

      player.position.x += amountDragged 

      if player.position.x > CGRectGetMaxX(gameArea) - player.size.width/2{ 

       player.position.x = CGRectGetMaxX(gameArea) - player.size.width/2 


      } 

      if player.position.x < CGRectGetMinX(gameArea) + player.size.width/2{ 
       player.position.x = CGRectGetMinX(gameArea) + player.size.width/2  

Alors quelqu'un peut-il soit modifier mon code pour moi d'utiliser l'accéléromètre pour contrôler le navire ou nous pourrions parler sur Skype où je voudrais un peu d'aide. Mon Skype est RoobTheMan.

// GameScene.swift 
// One Mission 
// 
// Created by Robert Smith on 7/8/16. 
// Copyright (c) 2016 RobTheMan. All rights reserved. 
// 

import SpriteKit 

class GameScene: SKScene, SKPhysicsContactDelegate{ 


    let bulletSound = SKAction.playSoundFileNamed("BulletSound.wav" , waitForCompletion: false) 


    struct physicsCategories { 
     static let None : UInt32 = 0 
     static let Player : UInt32 = 0b1 // 1 
     static let Bullet : UInt32 = 0b10 //2 
     static let Enemy : UInt32 = 0b100 // 4 

    } 

    let player = SKSpriteNode(imageNamed: "playerShip") 


    func random() -> CGFloat { 
     return CGFloat(Float(arc4random())/0xFFFFFFFF) 

    } 
    func random(min min: CGFloat, max: CGFloat) -> CGFloat{ 
     return random() * (max - min) + min 
    }  


    let gameArea: CGRect 

    override init(size: CGSize) { 

     let maxAspectRatio: CGFloat = 16.0/9.0 
     let playableWidth = size.height/maxAspectRatio 
     let margin = (size.width - playableWidth)/2 
     gameArea = CGRect(x: margin, y: 0 , width: playableWidth, height: size.height) 


     super.init(size: size) 

    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 


    override func didMoveToView(view: SKView) { 

     self.physicsWorld.contactDelegate = self 

     let background = SKSpriteNode(imageNamed: "background") 
     background.size = self.size 
     background.position = CGPoint(x: self.size.width/2, y: self.size.height/2) 
     background.zPosition = 0 
     self.addChild(background) 


     player.setScale(1) 
     player.position = CGPoint(x: self.size.width/2, y: self.size.height * 0.2) 
     player.zPosition = 2 
     player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size) 
     player.physicsBody!.affectedByGravity = false 
     player.physicsBody!.categoryBitMask = physicsCategories.Player 
     player.physicsBody!.collisionBitMask = physicsCategories.None 
     player.physicsBody!.contactTestBitMask = physicsCategories.Enemy 
     self.addChild(player) 

     startNewLevel() 

    } 


    func startNewLevel(){ 


     let spawn = SKAction.runBlock(spawnEnemy) 
     let waitToSpawn = SKAction.waitForDuration(1) 
     let spawnSequence = SKAction.sequence([spawn, waitToSpawn]) 
     let spawnForever = SKAction.repeatActionForever(spawnSequence) 
     self.runAction(spawnForever) 


    } 


    func fireBullet() { 

     let bullet = SKSpriteNode(imageNamed: "bullet") 
     bullet.setScale(0.8) 
     bullet.position = player.position 
     bullet.zPosition = 1 
     bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.size) 
     bullet.physicsBody!.affectedByGravity = false 
     bullet.physicsBody!.categoryBitMask = physicsCategories.Bullet 
     bullet.physicsBody!.collisionBitMask = physicsCategories.None 
     bullet.physicsBody!.contactTestBitMask = physicsCategories.Enemy 
     self.addChild(bullet) 

     let moveBullet = SKAction.moveToY(self.size.height + bullet.size.height, duration: 1) 
     let deleteBullet = SKAction.removeFromParent() 
     let bulletSequence = SKAction.sequence([bulletSound, moveBullet, deleteBullet]) 
     bullet.runAction(bulletSequence) 


    } 


    func spawnEnemy(){ 

     let randomXStart = random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) 
     let randomXEnd = random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) 

     let startPoint = CGPoint(x: randomXStart, y: self.size.height * 1.2) 
     let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 0.2) 

     let enemy = SKSpriteNode(imageNamed: "enemyShip") 
     enemy.setScale(1) 
     enemy.position = startPoint 
     enemy.zPosition = 2 
     enemy.physicsBody = SKPhysicsBody(rectangleOfSize: enemy.size) 
     enemy.physicsBody!.affectedByGravity = false 
     enemy.physicsBody!.categoryBitMask = physicsCategories.Enemy 
     enemy.physicsBody!.categoryBitMask = physicsCategories.None 
     enemy.physicsBody!.contactTestBitMask = physicsCategories.Player | physicsCategories.Bullet 
     self.addChild(enemy) 

     let moveEnemy = SKAction.moveTo(endPoint, duration: 1.5) 

     let deleteEnemy = SKAction.removeFromParent() 
     let enemySequence = SKAction.sequence([moveEnemy, deleteEnemy]) 
     enemy.runAction(enemySequence) 

     let dx = endPoint.x - startPoint.x 
     let dy = endPoint.y - startPoint.y 
     let amountToRotate = atan2(dy, dx) 
     enemy.zRotation = amountToRotate 

    } 


    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

     fireBullet() 
    } 


    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

     for touch: AnyObject in touches{ 

      let pointOfTouch = touch.locationInNode(self) 
      let previousPointOfTouch = touch.previousLocationInNode(self) 

      let amountDragged = pointOfTouch.x - previousPointOfTouch.x 

      player.position.x += amountDragged 

      if player.position.x > CGRectGetMaxX(gameArea) - player.size.width/2{ 

       player.position.x = CGRectGetMaxX(gameArea) - player.size.width/2 


      } 

      if player.position.x < CGRectGetMinX(gameArea) + player.size.width/2{ 
       player.position.x = CGRectGetMinX(gameArea) + player.size.width/2 
      } 

     } 

    } 

} 

Répondre

0

Ne vous inquiétez pas, c'est assez simple. D'abord vous devez faire import CoreMotion en haut du fichier Swift où les autres importations se produisent - en dehors de la définition de la classe.

Effectuez ensuite:

// GameScene.swift 
// One Mission 
// 
// Created by Robert Smith on 7/8/16. 
// Copyright (c) 2016 RobTheMan. All rights reserved. 
// 

import SpriteKit 
import CoreMotion 
class GameScene: SKScene, SKPhysicsContactDelegate{ 


let bulletSound = SKAction.playSoundFileNamed("BulletSound.wav" , waitForCompletion: false) 
var motionTimer = NSTimer() 
var motionManager: CMMotionManager = CMMotionManager() 

struct physicsCategories { 
    static let None : UInt32 = 0 
    static let Player : UInt32 = 0b1 // 1 
    static let Bullet : UInt32 = 0b10 //2 
    static let Enemy : UInt32 = 0b100 // 4 

} 

let player = SKSpriteNode(imageNamed: "playerShip") 


func random() -> CGFloat { 
    return CGFloat(Float(arc4random())/0xFFFFFFFF) 

} 
func random(min min: CGFloat, max: CGFloat) -> CGFloat{ 
    return random() * (max - min) + min 
} 




let gameArea: CGRect 

override init(size: CGSize) { 

    let maxAspectRatio: CGFloat = 16.0/9.0 
    let playableWidth = size.height/maxAspectRatio 
    let margin = (size.width - playableWidth)/2 
    gameArea = CGRect(x: margin, y: 0 , width: playableWidth, height: size.height) 


    super.init(size: size) 

} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
} 




override func didMoveToView(view: SKView) { 
    motionManager.deviceMotionUpdateInterval = 0.01 
    motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{ 
     deviceManager, error in 
    }) 
    motionManager.startAccelerometerUpdates() 
    motionTimer = NSTimer.scheduledTimerWithTimeInterval(0.001, target:self, selector: Selector("calculateMotion"), userInfo: nil, repeats: true) 
    self.physicsWorld.contactDelegate = self 

    let background = SKSpriteNode(imageNamed: "background") 
    background.size = self.size 
    background.position = CGPoint(x: self.size.width/2, y: self.size.height/2) 
    background.zPosition = 0 
    self.addChild(background) 


    player.setScale(1) 
    player.position = CGPoint(x: self.size.width/2, y: self.size.height * 0.2) 
    player.zPosition = 2 
    player.physicsBody = SKPhysicsBody(rectangleOfSize: player.size) 
    player.physicsBody!.affectedByGravity = false 
    player.physicsBody!.categoryBitMask = physicsCategories.Player 
    player.physicsBody!.collisionBitMask = physicsCategories.None 
    player.physicsBody!.contactTestBitMask = physicsCategories.Enemy 
    self.addChild(player) 

    startNewLevel() 

} 
func calculateMotion() { 
    if let data = motionManager.accelerometerData { 
     // you could do (you can change 2 to whatever you want - that makes it x times as fast/sensitive) 
     player.position.x+=(CGFloat(2)*CGFloat(data.acceleration.x)) 
     if data.acceleration.x >= 0.8 || data.acceleration.x <= -0.8{ 
      //Make whatever you want to happen when there is acceleration happen here 
     } 
    } 
} 

func startNewLevel(){ 


    let spawn = SKAction.runBlock(spawnEnemy) 
    let waitToSpawn = SKAction.waitForDuration(1) 
    let spawnSequence = SKAction.sequence([spawn, waitToSpawn]) 
    let spawnForever = SKAction.repeatActionForever(spawnSequence) 
    self.runAction(spawnForever) 


} 


func fireBullet() { 

    let bullet = SKSpriteNode(imageNamed: "bullet") 
    bullet.setScale(0.8) 
    bullet.position = player.position 
    bullet.zPosition = 1 
    bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.size) 
    bullet.physicsBody!.affectedByGravity = false 
    bullet.physicsBody!.categoryBitMask = physicsCategories.Bullet 
    bullet.physicsBody!.collisionBitMask = physicsCategories.None 
    bullet.physicsBody!.contactTestBitMask = physicsCategories.Enemy 
    self.addChild(bullet) 

    let moveBullet = SKAction.moveToY(self.size.height + bullet.size.height, duration: 1) 
    let deleteBullet = SKAction.removeFromParent() 
    let bulletSequence = SKAction.sequence([bulletSound, moveBullet, deleteBullet]) 
    bullet.runAction(bulletSequence) 


} 


func spawnEnemy(){ 

    let randomXStart = random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) 
    let randomXEnd = random(min: CGRectGetMinX(gameArea), max: CGRectGetMaxX(gameArea)) 

    let startPoint = CGPoint(x: randomXStart, y: self.size.height * 1.2) 
    let endPoint = CGPoint(x: randomXEnd, y: -self.size.height * 0.2) 

    let enemy = SKSpriteNode(imageNamed: "enemyShip") 
    enemy.setScale(1) 
    enemy.position = startPoint 
    enemy.zPosition = 2 
    enemy.physicsBody = SKPhysicsBody(rectangleOfSize: enemy.size) 
    enemy.physicsBody!.affectedByGravity = false 
    enemy.physicsBody!.categoryBitMask = physicsCategories.Enemy 
    enemy.physicsBody!.categoryBitMask = physicsCategories.None 
    enemy.physicsBody!.contactTestBitMask = physicsCategories.Player | physicsCategories.Bullet 
    self.addChild(enemy) 

    let moveEnemy = SKAction.moveTo(endPoint, duration: 1.5) 

    let deleteEnemy = SKAction.removeFromParent() 
    let enemySequence = SKAction.sequence([moveEnemy, deleteEnemy]) 
    enemy.runAction(enemySequence) 

    let dx = endPoint.x - startPoint.x 
    let dy = endPoint.y - startPoint.y 
    let amountToRotate = atan2(dy, dx) 
    enemy.zRotation = amountToRotate 



} 


override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    fireBullet() 
} 


override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    for touch: AnyObject in touches{ 

     let pointOfTouch = touch.locationInNode(self) 
     let previousPointOfTouch = touch.previousLocationInNode(self) 

     let amountDragged = pointOfTouch.x - previousPointOfTouch.x 

     player.position.x += amountDragged 

     if player.position.x > CGRectGetMaxX(gameArea) - player.size.width/2{ 

      player.position.x = CGRectGetMaxX(gameArea) - player.size.width/2 


     } 

     if player.position.x < CGRectGetMinX(gameArea) + player.size.width/2{ 
      player.position.x = CGRectGetMinX(gameArea) + player.size.width/2 
     } 

    } 

} 


} 

Vous pouvez changer le 0,8 à autre chose plus tard -> Plus le nombre est inférieur au seuil d'accélération. Vous pouvez également changer x à et ou z - dépend de l'axe de votre téléphone pour lequel vous voulez détecter l'accélération.

Si vous avez d'autres questions ou ne hésitez pas à me laisser savoir :)

+0

J'ai deux questions, où je mettrais le code ci-dessus après avoir importé CoreMotion et comment pourrais-je relier cela à la gauche et le bon mouvement (j'ai seulement besoin de gauche et de droite) de mon SKSpriteNode? – Rob

+0

@Rob Je ne sais pas exactement ce que vous essayez d'atteindre - je pense que vous pouvez vouloir la sensibilité d'inclinaison et non l'accéléromètre. Pour diriger un vaisseau spatial dans un jeu, l'utilisation d'un accéléromètre serait très désagréable - l'utilisateur devrait continuer à déplacer son téléphone d'avant en arrière. Mais vous mettriez le code ci-dessus où votre code actuel est maintenant - dans la déclaration de classe. Assurez-vous de vous débarrasser de l'une des fonctions de didMoveToView - mettez le code que vous avez dans votre projet actuel dans celui du code que j'ai collé ci-dessus. Vous ne pouvez pas avoir deux de ces appels de fonction. – CoolPenguin

+0

@Rob Vous pourriez faire quelque chose comme player.position.x + = data.acceleration.x Ce serait dans la boucle if let mais en dehors de la boucle if si elle est supérieure à 0.8 – CoolPenguin