2017-02-15 2 views
0

Я создаю игру, где есть квадратная фигура, и каждый раз, когда игрок нажимает на квадрат, он переходит в сцену GameOver. Все, что я хочу сделать, это когда квадратная фигура используется, ей будет выделено другое положение экрана, которое будет использоваться на квадратах.Как сделать форму, чтобы не перейти в GameOver? -SpriteKit

Here is my code:

let touch:UITouch = touches.first! 
    let positionInScene = touch.location(in: self) 
    let touchedNode = self.atPoint(positionInScene) 




    if let name = touchedNode.name 
    { 
     //The first ball that shows up 
     if name == "startball" 
     { 
      print("Touched", terminator: "") 
      addBall(ballSize) 




      self.addChild(score) 
     } 
     else if name == "shape"{ 

      scoreCount += 1 

      addBall(ballSize) 




      audioPlayer.play() 

     } 





    } 



    else { 

     let scene = GameOver(size: self.size) 
     scene.setMyScore(0) 
     let skView = self.view! as SKView 
     skView.ignoresSiblingOrder = true 
     scene.scaleMode = .resizeFill 
     scene.size = skView.bounds.size 
     scene.setMessage("You Lost!") 

     scene.setEndGameMode(va) 
     gameTimer.invalidate() 
     shownTimer.invalidate() 
     print(" timers invalidated ", terminator: "") 
     ran = true 
     skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25)) 
    } 








    if firstTouch { 
     shownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(GameScene.decTimer), userInfo: nil, repeats: true) 
     gameTimer = Timer.scheduledTimer(timeInterval: TIME_INCREMENT, target:self, selector: Selector("endGame"), userInfo: nil, repeats: false) 
     firstTouch = false 



    } 

    if touchCount > 5 { 

     for touch: AnyObject in touches { 
      let skView = self.view! as SKView 
      skView.ignoresSiblingOrder = true 
      var scene: Congratz! 
      scene = Congratz(size: skView.bounds.size) 
      scene.scaleMode = .aspectFill 
      skView.presentScene(scene, transition: SKTransition.doorsOpenHorizontal(withDuration: 1.0)) 



     } 




    } 
    touchCount += 1 



} 




    override func update(_ currentTime: TimeInterval) { 
    super.update(currentTime) 




} 

func endGame(){ 
    shownTimer.invalidate() 
    gameTimer.invalidate() 
    let scene = GameOver(size: self.size) 
    scene.setMyScore(scoreCount) 
    if let skView = self.view { 
     skView.ignoresSiblingOrder = false 
     scene.scaleMode = .resizeFill 
     scene.size = skView.bounds.size 
     scene.setMessage("Times up") 

     skView.presentScene(scene, transition: SKTransition.crossFade(withDuration: 0.25)) 
    } 

} 







     override func addBall(_ size: Int) { 
     // Add the ball 
     let currentBall = SKShapeNode(circleOfRadius: CGFloat(size)) 

    let viewMidX = view!.bounds.midX 
    let viewMidY = view!.bounds.midY 

    currentBall.fillColor = pickColor() 



    currentBall.position = randomBallPosition() 




    if scoreCount != 0{ 
     if scoreCount == 1{ 
      self.addChild(score) 
      self.addChild(timeLeftLabel) 
      self.childNode(withName: "welcome")?.removeFromParent() 
     } 
     self.childNode(withName: "ball")?.run(getSmaller) 
     self.childNode(withName: "ball")?.removeFromParent() 

    } 
    currentBall.name = "ball" 


    self.addChild(currentBall) 
} 

    func addSquare(_ size: Int) { 
    // Add the square 
    let shape = SKShapeNode(rectOf: CGSize(width:CGFloat(size), height:CGFloat(size))) 

    shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath 

    shape.fillColor = pickColor() 

    shape.position = randomBallPosition() 

    shape.name = "shape" 

    self.addChild(shape) 

} 


    func randomBallPosition() -> CGPoint { 
    let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1))) 
    let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1))) 


    return CGPoint(x: xPosition, y: yPosition) 

} 

ответ

1

То, что я хотел бы предложить, было бы сделать что-то вроде enum для различных форм, так что вы можете отслеживать, какую форму вы используете.

enum GameShape: Int { 

    case circle = 0 
    case square = 1 

} 

Затем создайте GameShape свойство в верхней части GameScene:

var currentShape: GameShape = .circle 

Тогда вы могли бы создать своего рода updateShape метода, который вы могли бы назвать в методе touchesBegan вместо того, чтобы просто addBall

func updateShape(shapeSize: CGSize) { 

    switch currentShape { 
     case .circle: 
      addCircle(shapeSize) 
     case .square: 
      addSquare(shapeSize) 
     default: 
      break 
    } 

    // However you want to setup the condition for changing shape 
    if (condition) { 
     currentShape = .square 
    } 

} 

func addBall(_ size: CGSize) { 
    // Add the ball 
} 

func addSquare(_ size: CGSize) { 
    // Add the square 
} 

Теперь в вашем методе touchesBegan вместо вызова addBall(size, вы могли бы назвать updateShape:

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

    // Setup your code for detecting position for shape origin 
    updateShape(shapeSize) 

} 

EDIT - Ваш код бардак. Вы действительно должны потратить время, чтобы убедиться, что оно правильно отформатировано, когда вы его отправляете, иначе вам действительно очень сложно помочь. Отступы помогают увидеть, где начинается и заканчивается закрытие. Из того, что я могу сказать, похоже, что у вас есть две или более функции, вложенные в ваш метод addBall. Это не хорошо. Я изо всех сил старался очистить его для вас. Вы все еще нужно написать код, чтобы сделать форму квадрата, но у меня привести вас в правильном направлении, чтобы начать, чтобы это произошло:

func addBall(_ size: CGSize) { 
    // Add the ball 
    let currentBall = SKShapeNode(circleOfRadius: CGFloat(size)) 

    let viewMidX = view!.bounds.midX 
    let viewMidY = view!.bounds.midY 

    currentBall.fillColor = pickColor() 

    shape.path = UIBezierPath(roundedRect: CGRect(x: 64, y: 64, width: 160, height: 160), cornerRadius: 50).cgPath 

    shape.fillColor = pickColor() 

    currentBall.position = randomBallPosition() 
    shape.position = randomBallPosition() 

    self.addChild(shape) 

    if scoreCount != 0{ 
     if scoreCount == 1{ 
      self.addChild(score) 
      self.addChild(timeLeftLabel) 
      self.childNode(withName: "welcome")?.removeFromParent() 
     } 
     self.childNode(withName: "ball")?.run(getSmaller) 
     self.childNode(withName: "ball")?.removeFromParent() 

    } 
    currentBall.name = "ball" 
    shape.name = "ball" 

    self.addChild(currentBall) 
} 

func addSquare(_ size: CGSize) { 
    // Add the square 
} 

func randomBallPosition() -> CGPoint { 
    let xPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxX)! + 1))) 
    let yPosition = CGFloat(arc4random_uniform(UInt32((view?.bounds.maxY)! + 1))) 


    return CGPoint(x: xPosition, y: yPosition) 

} 

Теперь приведенный выше код предполагает, что вы имеете некоторое свойство с именем shape, потому что из того, что я мог сказать вам, никогда не явным образом не создавал это, но вы начинаете манипулировать им.

+0

addSquare, он получает ошибку: «использование локальной переменной addSquare перед ее объявлением». –

+0

@ D.W - Может быть, вы могли бы показать код, который вы использовали для его реализации? Потому что 'addSquare' - это функция, а не переменная - поэтому я думаю, что, возможно, вы синтаксис неверен – Pierce

+0

Можете ли вы проверить мой обновленный вопрос. Я обновил его. –

Смежные вопросы