【问题标题】:How to add a SKSpriteNode to the scene in Swift?如何在 Swift 中将 SKSpriteNode 添加到场景中?
【发布时间】:2016-02-26 21:14:28
【问题描述】:

我尝试将SKSpriteNode 子类化为GameObject,并且我想在游戏场景类之外实例化对象。这是我从SKSpriteNode 派生的GameObject 代码:

import SpriteKit

public class GameObject: SKSpriteNode {

    init( texture: SKTexture?, color: UIColor, size: CGSize, position:CGPoint, name:String ) 
    {   
        objectSize = size;
        objectName = name;
        objectSprite = texture;
        //call superclass here
        super.init(texture: texture, color: color, size: size);
        self.position = position;
    }

    convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _object:String )// Default initializer
    {
        let texture = SKTexture(imageNamed: _object);
        let position = CGPoint(x:_x, y:_y);
        self.init(  texture: texture,color: UIColor(),size: texture.size(), position: position, name: _object);
    }

    //Overloaded initializer with size as extra argument
    convenience init(_ _x:CGFloat, _ _y:CGFloat, _ _size:Int, _ _object:String)
    {
        //size for the SKSpriteNode.
        let texture = SKTexture(imageNamed: _object);
        let position = CGPoint(x:_x, y:_y);
        self.init(  texture: texture, color: UIColor(), size: CGSize(width: _size, height: _size),position: position, name: _object);
    }

要实例化从GameObject 派生的播放器,我必须这样写:

let player = PlayerShip(100, 100, "PlayerShip")
addChild(player)

但是,addChild() 在gameScene 之外不起作用。我的目标是从PlayerShip 类中实例化子弹,但我不知道如何。有人有建议吗?

【问题讨论】:

  • 从问题中不清楚你想做什么。你在什么时候将此方法称为addChild?以及更多您调用它的代码。更详细地描述创建对象的目的。所以你不是在场景和另一个对象中创建它们,然后将它们添加到场景中?

标签: swift sprite-kit subclass skspritenode addchild


【解决方案1】:

如果您想在 GameScene 之外执行此操作,您需要一个 kind go 全局属性,该属性具有对 GameScene 的引用。然后你可以调用:

myGameScene.AddChild(player)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2021-08-11
    • 1970-01-01
    相关资源
    最近更新 更多