【发布时间】:2018-01-12 05:44:19
【问题描述】:
我正在为 IOS 编写一个子弹地狱类型的游戏,其中有多个敌人朝玩家冲过来。对于敌人,我创建了一个名为 Enemy 的自定义类,它是 SKSpritenode 类的子类。
class Enemy : SKSpriteNode {
var type : String;
var health : Int;
var armor : Int;
var healthBar : HealthBar; //The HealthBar Class
init(type: String, position: CGPoint, texture : SKTexture, color: UIColor, size: CGSize){
self.type = type;
self.health = enemyHealths[self.type]!
self.armor = enemyArmors[self.type]!
self.healthBar = HealthBar(healthBarWidth: 40, healthBarHeight: 4, hostile: true, health: self.health, maxHealth: self.health, position: position) //Initialize HealthBar
super.init(texture: texture, color: color, size: size)
self.position = position;
self.physicsBody = SKPhysicsBody(rectangleOf: self.size);
self.physicsBody?.affectedByGravity = false;
self.physicsBody?.collisionBitMask = 0;
self.physicsBody?.isDynamic = true;
self.addChild(self.healthBar) //Add HealthBar Instance
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(currentTime: TimeInterval){
}
}
在这个类中,我初始化了另一个类,一个 HealthBar 类,它也是 SKSPritenode 类的子类,但是当我尝试将它作为子类添加到 Enemy 实例时,它会显示在屏幕的最右侧.我想知道是否有特定的子位置机制导致这种情况发生,或者只是代码中的错误。我能想到的可能导致此错误的一件事是,当我更新 HealthBar 位置时,我将其位置设置为与 Enemy 相同的位置,后者作为子项添加到 GameScene 中。当 Healthbar 作为子项添加到较小的 Enemy 时,这可能会导致该坐标不可用的错误。
正如您所见,Enemy 生成得很好,但 HealthBar 位于屏幕的最右侧,而不是它应该在 Enemy 的正上方。
【问题讨论】:
标签: ios swift inheritance sprite-kit