问题
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