How to add a SKSpriteNode to the scene in Swift?

我的未来我决定 提交于 2020-01-06 21:59:33

问题


I tried to subclass SKSpriteNode into GameObject and I would like to instantiate objects outside the game scene class. Here is my GameObject code derived from SKSpriteNode:

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);
    }

To instantiate a player derived from GameObject, I have to write:

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

However, addChild() does not work outside gameScene. My goal is to instantiate bullets from the PlayerShip class, but i can't figure out how. Does anyone have a suggestion?


回答1:


If you want to do this outside of GameScene you need a kind go global property which has a reference to the GameScene. Then you can call:

myGameScene.AddChild(player)


来源:https://stackoverflow.com/questions/33893502/how-to-add-a-skspritenode-to-the-scene-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!