ios - Swift 3 (SpriteKit) 从自定义类中将子项添加到 GameScene

标签 ios swift inheritance sprite-kit

我正在为 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 中。当生命条作为子项添加到较小的敌人时,这可能会导致该坐标不可用的错误。

Swift Child Bug

正如您所看到的,敌人生成得很好,但生命栏位于屏幕的最右侧,而不是应在敌人上方。

最佳答案

好吧,事实证明我的怀疑是正确的。由于您要向较小的敌人实例添加一个子级,因此坐标 CGPoint(x: 0, y: 0)对应于敌人实例的中心。因此,为了让 HealthBar 位于敌人实例上方,您只需将其位置设置为上述坐标,并在 Y 值中添加一个小的正偏移量。

关于ios - Swift 3 (SpriteKit) 从自定义类中将子项添加到 GameScene,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48220246/

相关文章:

ios - 如何通过php web服务成功登录

ios - 将 UIButton 添加到 UIDatePicker

ios - 请求交易时出错

swift - 如何将Alamofire生成的数据从tableview推送到webview

ios - 通过API在Google日历上创建重复事件

不继承属性的Python子类

ios - 如何将 CoreNFC 与 ApplicationDelegate 一起用于 Qt?

Swift - 无法更改 UILabel 中的字体样式

JavaScript继承: using __proto__ within constructor function,而不是构造函数的prototype属性

java - 只用一个类或多个类实现接口(interface)