我尝试将 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
类中的子弹,但我不知道如何实现。有人有建议吗?
最佳答案
如果您想在 GameScene 之外执行此操作,您需要一种具有对 GameScene 引用的全局属性。然后你可以调用:
myGameScene.AddChild(player)
关于swift - 如何在 Swift 中添加 SKSpriteNode 到场景中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33893502/