如何在Swift中将SKSpriteNode添加到场景?
我试图将 SKSpriteNode
子类化为 GameObject
,我想实例化游戏场景类之外的对象。这是从 SKSpriteNode
派生的我的 GameObject
代码:
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);
}
要实例化从 GameObject派生的玩家
,我必须写:
To instantiate a player derived from GameObject
, I have to write:
let player = PlayerShip(100, 100, "PlayerShip")
addChild(player)
但是, addChild()
在 gameScene
之外不起作用。我的目标是实例化 PlayerShip
类的项目符号,但我不知道如何实现。
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?
如果您想在GameScene之外进行此操作,则需要一个go go属性,该属性具有参考GameScene。然后您可以调用:
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)