我是新手,最近才刚开始学习。
目前,我在生成随机对象方面遇到麻烦。一个是顶部,另一个是底部,我想在两者之间随机选择,并继续重复该操作。
到目前为止,我可以使对象从右向左连续滚动,然后离开屏幕。但是使用我的代码,它将生成顶部或底部的对象,然后再没有其他对象。它将重复产生它首先选择的那个。
不确定是否需要将其从didMove(to view: Skview)
函数移至另一个函数,或者是否有更好的方法对此进行编码。
下面是我用来使它们连续一个接一个地重复的代码。
这是override func didMove(to view: SKView)
中的代码:
let randomArray = [spawnAndDelayForeverUpObject, spawnAndDelayForeverDownProject]
self.run(randomArray.randomElement()!)
let randomObject = randomArray.randomElement()!
self.run(SKAction.repeatForever(randomObject))
我对我的第一个项目感到困惑,所以我尝试了一个新项目,下面是我的代码。
我仍然不明白如何随机选择像几秒钟那样显示红色或蓝色框而不是两个框。我在苹果开发者网站上,从游戏工具包编程指南中找到了随机化方法,我将在其中randomization guide apple
进行阅读。GameScene类:SKScene,SKPhysicsContactDelegate {
let blueBox = SKSpriteNode(color: UIColor.blue, size: CGSize(width: 50, height: 50))
let redBox = SKSpriteNode(color: UIColor.red, size: CGSize(width: 25, height: 25))
override func didMove(to view: SKView) {
self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.0)
physicsBody = SKPhysicsBody.init(edgeLoopFrom: frame)
run(SKAction.repeatForever(SKAction.sequence([SKAction.run(spawnRedBox), SKAction.wait(forDuration: (5)), SKAction.run(removeRedBox)])))
run(SKAction.repeatForever(SKAction.sequence([SKAction.run(spawnBlueBox), SKAction.wait(forDuration: (5)), SKAction.run(removeBlueBox)])))
}
func removeBlueBox() {
blueBox.removeFromParent()
}
func removeRedBox() {
redBox.removeFromParent()
}
func spawnBlueBox() {
print("spawnBlueBoxFuncCalled")
blueBox.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: blueBox.size.width, height: blueBox.size.height))
blueBox.physicsBody?.affectedByGravity = false
blueBox.physicsBody?.isDynamic = true
let posTwo = SKAction.move(to: CGPoint(x: frame.minX + 50, y: frame.midY + 100), duration: 0.0)
let Position = posTwo
let move = SKAction.move(by: CGVector(dx: frame.size.width, dy: 0), duration: 5.0)
let moveRemoveMoveBack = SKAction.sequence([Position, move])
let repeatMoving = SKAction.repeatForever(moveRemoveMoveBack)
blueBox.run(repeatMoving)
self.addChild(blueBox)
}
func spawnRedBox() {
print("spawnRedBoxFuncCalled")
redBox.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: redBox.size.width, height: redBox.size.height))
redBox.physicsBody?.affectedByGravity = false
redBox.physicsBody?.isDynamic = true
let posOne = SKAction.move(to: CGPoint(x: frame.minX + 50, y: frame.midY), duration: 0.0)
let Position = posOne
let move = SKAction.move(by: CGVector(dx: frame.size.width, dy: 0), duration: 5.0)
let moveRemoveMoveBack = SKAction.sequence([Position, move])
let repeatMoving = SKAction.repeatForever(moveRemoveMoveBack)
redBox.run(repeatMoving)
self.addChild(redBox)
//Array example
}
`
答案 0 :(得分:0)
问题是您选择了一个对象并将其分配给randomObject
,但没有为run
函数将其重新分配给新值。 SKAction.repeatForever
调用将重复使用randomObject
及其分配的值。您可以通过重复运行相同的代码来解决此问题。为此,您可以将代码移至某个函数,然后使用Timer重复调用该函数。或者,您可以使用给定的答案之一here。