【发布时间】: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