如何将Sprite作为类添加到场景中?

时间:2016-02-03 21:53:53

标签: swift class sprite-kit

我想在我的游戏场景中添加一个精灵。但问题是,我想多次添加精灵,所以我想从精灵中创建一个类,我不想使用场景编辑器

所以我的班级被称为Passenger,这是它的代码

import SpriteKit

class PassengerNode: SKSpriteNode, CustomPassengerNodeEvents {

init(texture: SKTexture?, color: UIColor, size: CGSize) {
    <#code#>
}  
}

在我的游戏场景中,我想添加类似

的类
let passenger = PassengerNode()

但我想知道如何在Passenger Class中设置纹理?我想不出这个?任何提示或建议?

提前致谢

2 个答案:

答案 0 :(得分:1)

您只需在调用super.init之前设置所有属性。你可以创建一个默认的init()函数,然后设置你的属性,然后用纹理等调用super.init。

Concat

您需要致电async,因为它是class SomeSprite: SKSpriteNode { init() { let spriteTexture: SKTexture = SKTexture(imageNamed: "someImage") let spriteSize = spriteTexture.size() super.init(texture: spriteTexture, color: UIColor.clearColor(), size: spriteSize) } } 的指定初始值设定项。但是您应该知道,您可以从子类中的另一个init(texture:color:size)函数调用指定的初始值设定项,在本例中为空SKSpriteNode实现。只需设置默认值并创建精灵。

答案 1 :(得分:1)

通过子类化SKSpriteNode,你肯定是在正确的轨道上。我有一个标准模板,我在创建一个看起来像这样的SKSpriteNode子类时使用。另外,我用一个可以从类外部调用的函数来扩充它,将纹理更改为你喜欢的任何颜色:

import Foundation
import SpriteKit

class SubclassedSKSpriteNode: SKSpriteNode {
    init() {
        let texture = SKTexture(imageNamed: "whateverImage.png")
        super.init(texture: texture, color: UIColor.clearColor(), size: texture.size())
        userInteractionEnabled = true
    }

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

   // MARK: - Change Texture

   func updateTexture(newTexture: SKTexture) {
      self.texture = newTexture
   }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let location = (touches.first! ).locationInNode(scene!)
        position = scene!.convertPoint(location, toNode: parent!)

        print("touchesBegan: \(location)")
    }

    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let location = (touches.first! ).locationInNode(scene!)
        position = scene!.convertPoint(location, toNode: parent!)

        print("touchesMoved: \(location)")

    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        let location = (touches.first! ).locationInNode(scene!)
        position = scene!.convertPoint(location, toNode: parent!)

        print("touchesEnded: \(location)")
    }
}

此外,要将此按钮添加到SKScene(或任何其他SKNode):

let button = SubclassedSKSpriteNode()
button.position = CGPointMake(420, 300)
addChild(button)

然后,如果您想要更改纹理,请调用:

button.updateTexture(newTexture)

HTH!