如何在屏幕上正确管理精灵组 [英] How to properly manage groups of sprites onscreen

查看:66
本文介绍了如何在屏幕上正确管理精灵组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Swift构建我的第一个游戏,我想知道如何一次处理多个屏幕上的精灵。我的游戏不断地用精灵推送精灵到 addChild ,所以有很多活跃的。我意识到我没有一种同时影响所有这些的正确方法 - 比如我想立刻影响所有敌人精灵的物理特性。到目前为止,我在 GameScene 的开头创建了一个空数组 var enemySprites = [enemyType1]()并且已经将精灵实例附加到而不是使用 addChild 将它们直接绘制到场景中。但是,我无法简单地循环并将它们绘制到屏幕上:

I'm building my first game in Swift and I wanted to know how to go about handling multiple on screen sprites at once. My game pushes sprites on to screen with addChild continuously, so there are many active at once. I realized that I didn't have a proper way of simultaneously affecting all of them- like if I wanted to affect a physics property of all enemy sprites at once. So far I created an empty array var enemySprites = [enemyType1]() at the begining of GameScene and have been appending the sprite instances to it instead of using addChild to draw them directly to the scene. However, I'm not able to simply loop through and draw them to screen with:

    for enemy in enemySprites{
        addChild(enemy)
    }

此位代码位于覆盖func update(currentTime:CFTimeInterval)函数,所以也许我只是放错了地方?如何解决这个问题的任何帮助都会很棒!

this bit of code is in the override func update(currentTime: CFTimeInterval) function, so maybe I'm just misplacing it? Any help on how to go about this would be great!

推荐答案

Sam,

以下是一些示例代码,用于在您的生命达到0时更新敌人:

Here's some sample code to update enemies when your lives reach 0:

首先,我们在生命中设置属性观察者属性所以我们可以在你失去所有生命时调用一个函数:

First, we set a property observer on the lives property so we can call a function when you lose all lives:

var lives = 3 {
    didSet {
        if lives == 0 {
        updateEnemies()
    }
}

然后是一个枚举所有敌人并将每个敌人的速度改为(0,0)的函数:

And then a function to enumerate over all the enemies and change each one's velocity to (0, 0):

func update enemies() {
        enumerateChildNodesWithName("type1") {
            node, stop in
            let enemy = node as! SKSpriteNode
            enemy.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
        }
}

这篇关于如何在屏幕上正确管理精灵组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆