加速度计介绍?代码修复?

时间:2016-07-09 22:31:14

标签: ios iphone xcode accelerometer move

最新错误:

enter image description here

我最近一直在开发一个带有教程的应用程序,并且我希望转向教程。但我接下来没有SpriteKit的经验,所以我想帮助使用加速计来控制应用程序上的某些内容。

你在游戏中控制太空飞船的部分在这里:

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    

所以任何人都可以编辑我的代码让我使用加速度计来控制船只,或者我们可以通过Skype与我交谈,我希望得到一些帮助。我的Skype是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
            }

        }

    }

}

1 个答案:

答案 0 :(得分:0)

不要担心它非常简单。首先,您必须在Swift文件的顶部执行import CoreMotion,其他导入发生在外部类定义。

然后执行:

//  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
        }

    }

}


}

您可以稍后将 0.8 更改为其他内容 - &gt;数字越小,加速度阈值越低。您还可以将 x 更改为 y z - 这取决于您要检测加速度的电话轴。

如果您有任何其他问题或疑问,请随时告诉我:)