简体   繁体   中英

ios - Swift 2.2 - SpriteKit - sublassing SKSpriteNode class

For a puzzle game project on iOS, I try to subclass the SKSpriteNode class from SpriteKit with the following code:

class SKPuzzle: SKSpriteNode {
var name2:String = "";
}

I need to add other variables in SKSpriteNode like another name (name2) in this case. Here is the use I made of the class in a class type SKScene:

class GameScene: SKScene {

let background = SKSpriteNode(imageNamed: "BW")
var selectedNode = SKPuzzle()

override init(size: CGSize) {
super.init(size: size)

let imageNames = [sheet.Puzzle13() , sheet.Puzzle19(),sheet.Puzzle30(), 
sheet.Puzzle11(), sheet.Puzzle29(), sheet.Puzzle35() ]

for i in 0..<imageNames.count {
let imageName = imageNames[i]

let sprite = SKPuzzle(texture: imageName)

sprite.name = kAnimalNodeName
sprite.name2 = "\(i)"

let offsetFraction = (CGFloat(i) + 1.0)/(CGFloat(imageNames.count) + 1.0)

sprite.position = CGPoint(x: size.width * offsetFraction, y: size.height  / 2)
sprite.zPosition = 1

background.addChild(sprite)

 }

}

I have the sprite object from the subclass SKPuzzle wich contains the new variable name2.

sprite.name2 = "\(i)"

The problem I have is the variable selectedNode (created with)

var selectedNode = SKPuzzle()

used later in the program contain always a nil value for the data name and name2. When I click on the jigsaw parts of the game, I get the following error:

fatal error: unexpectly found nil while unwrapping an optional value in the following function:

func panForTranslation(translation : CGPoint) {

let position = selectedNode.position

if selectedNode.name! == kAnimalNodeName {
selectedNode.position = CGPoint(x: position.x + translation.x * 2, y: position.y + translation.y * 2)


 }
}

selectedNode seems containing only nil values. The code is working fine when I just use the SKSpriteNode but failed with my SKPuzzle class.

Here is the whole code of the program:

import SpriteKit
import UIKit

private let kAnimalNodeName = "puzzle"
private let kdancing = "dancing"

class SKPuzzle: SKSpriteNode {
var name2:String = "";
 }

class GameScene: SKScene {



let background = SKSpriteNode(imageNamed: "BW")
var selectedNode = SKPuzzle()
var selectedVideo = SKVideoNode()



override init(size: CGSize) {
super.init(size: size)

// 1
self.background.name = kdancing
self.background.anchorPoint = CGPointZero
background.zPosition = 0
self.addChild(background)
//background.play()

// 2
let sheet = Statiques()

let sprite_dancing1 = SKSpriteNode(texture: sheet.Dancing1())
let sprite_dancing2 = SKSpriteNode(texture: sheet.Dancing2())
sprite_dancing1.name = kdancing
sprite_dancing2.name = kdancing


sprite_dancing1.position = CGPoint(x: 837, y: 752)
sprite_dancing1.zPosition = 1
sprite_dancing2.position = CGPoint(x: 1241, y: 752)
sprite_dancing2.zPosition = 1

background.addChild(sprite_dancing1)

background.addChild(sprite_dancing2)



let imageNames = [sheet.Puzzle13() , sheet.Puzzle19(), sheet.Puzzle30(), sheet.Puzzle11(), sheet.Puzzle29(), sheet.Puzzle35() ]

for i in 0..<imageNames.count {
let imageName = imageNames[i]

let sprite = SKPuzzle(texture: imageName)

sprite.name = kAnimalNodeName
sprite.name2 = "\(i)"

let offsetFraction = (CGFloat(i) + 1.0)/(CGFloat(imageNames.count) + 1.0)

sprite.position = CGPoint(x: size.width * offsetFraction, y: size.height / 2)
sprite.zPosition = 1

background.addChild(sprite)

 }

}

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

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

    for touch: AnyObject in touches {
    let positionInScene = touch.locationInNode(self)
        selectNodeForTouch(positionInScene)
        }
}


override func didMoveToView(view: SKView) {

    let gestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePanFrom:"))
    self.view!.addGestureRecognizer(gestureRecognizer)
}

func handlePanFrom(recognizer : UIPanGestureRecognizer) {

    if recognizer.state == .Began {
        var touchLocation = recognizer.locationInView(recognizer.view)
        touchLocation = self.convertPointFromView(touchLocation)

        self.selectNodeForTouch(touchLocation)
    } else if recognizer.state == .Changed {
        var translation = recognizer.translationInView(recognizer.view!)
        translation = CGPoint(x: translation.x, y: -translation.y)

        self.panForTranslation(translation)

        recognizer.setTranslation(CGPointZero, inView: recognizer.view)
    } else if recognizer.state == .Ended {

    }
}

func degToRad(degree: Double) -> CGFloat {
    return CGFloat(degree / 180.0 * M_PI)
}

func selectNodeForTouch(touchLocation : CGPoint) {
    // 1
    let touchedNode = self.nodeAtPoint(touchLocation)

    if touchedNode is SKPuzzle {
        // 2
        if !selectedNode.isEqual(touchedNode) {
            selectedNode.removeAllActions()
            selectedNode.runAction(SKAction.rotateToAngle(0.0, duration: 0.1))

            //selectedNode = touchedNode as! SKSpriteNode

            // 3
            if touchedNode.name! == kAnimalNodeName {
                let sequence = SKAction.sequence([SKAction.rotateByAngle(degToRad(-4.0), duration: 0.1),
                    SKAction.rotateByAngle(0.0, duration: 0.1),
                    SKAction.rotateByAngle(degToRad(4.0), duration: 0.1)])
                selectedNode.runAction(SKAction.repeatActionForever(sequence))
            }
        }
    }
}



func panForTranslation(translation : CGPoint) {
    let position = selectedNode.position

    if selectedNode.name! == kAnimalNodeName {
        selectedNode.position = CGPoint(x: position.x + translation.x * 2, y: position.y + translation.y * 2)


    }
 }

}

Thanks by advance for your help, I'm beginning to code with Swift on iOS.

When selectedNode is created by SKPuzzle() , name is nil.

You have to set selectedNode.name to some value in init method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM