Swift 如何在场景中生成对象?
我正在使用NSTimer生成场景中的对象。 例如:Swift 如何在场景中生成对象?,swift,sprite-kit,swift3,Swift,Sprite Kit,Swift3,我正在使用NSTimer生成场景中的对象。 例如: var enemyTimer = Timer() enemyTimer = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector:#selector(GameScene.enemyAppear),userInfo: nil, repeats: true) 但是我有一些麻烦。我需要生成没有时间间隔的新对象。我需要生成新的节点,它们之间有一定的距离。例如,对象之间有150个
var enemyTimer = Timer()
enemyTimer = Timer.scheduledTimer(timeInterval: 0.8, target: self, selector:#selector(GameScene.enemyAppear),userInfo: nil, repeats: true)
但是我有一些麻烦。我需要生成没有时间间隔的新对象。我需要生成新的节点,它们之间有一定的距离。例如,对象之间有150个点。我该怎么做?
对不起,我的英语…使用for循环并应用一些数学可以很容易地解决这个问题 假设您要生成5个敌人,每个敌人之间有100个像素,以y=0的水平线对齐:
for i in 0..<5 { // repeat 5 times
let enemy = SKSpriteNode(imageNamed: "insert your texture for the enemy here") // create new enemy
// here's the math part. When we generate the first enemy, i is 0, so it is at (0, 0).
// When it's time for the second enemy, i will be 1, so it will be placed at (100, 0)
enemy.position = CGPoint(x: 100 * i, y: 0)
enemy.anchorPoint = CGPoint(x: 0, y: 0)
self.addChild(enemy)
}
用于0中的i..您好!谢谢你的回答。我想从屏幕外创建新节点。例如:敌方.size=CGSize(x:160,y:80)敌方.position=CGPoint(x:250,y:1200)(我的场景大小=768x1024),敌方将移动到y:-100。我需要他们之间的距离。你能帮忙吗?谢谢@奈克斯。你不需要屏幕外精灵之间的距离!用户无论如何都看不到它们。每x秒移动一次精灵。这会使精灵之间看起来有空间。你可能想使用SKAction来繁殖敌人,因为NSTimer没有与游戏循环配对。例如,如果一个用户接到一个电话,当他在游戏中返回时,你的屏幕上将充满敌人。当然,您可以侦听通知并适当地使NSTimer无效/重新启动,但这是通过SKActions(或update:method)自动完成的。