我正在SpriteKit
建立游戏。该游戏将包括5个玩家,而不是为每个玩家编码SKAction
五次,我想将所有角色合并为一个,并为每个SKAction
编码一次,但下面的代码看起来不像上班。我错过了什么吗?
import SpriteKit
var player1 = SKSpriteNode()
var player2 = SKSpriteNode()
var player3 = SKSpriteNode()
var player4 = SKSpriteNode()
var player5 = SKSpriteNode()
var mainPlayer = SKSpriteNode()
// in view did load
player1 = mainPlayer
player2 = mainPlayer
player3 = mainPlayer
player4 = mainPlayer
player5 = mainPlayer
//in touches began
let rightMoveAction = SKAction.moveByX(50, y: 0, duration: 0.1)
mainPlayer.runAction(SKAction.repeatActionForever(rightMoveAction))
答案 0 :(得分:0)
我假设你的动机是缩短代码,因为mainPlayer
可能是一个复杂的节点,你不想复制代码5次。您没有显示将节点添加到场景的位置,但是当您尝试添加player2
因为已添加时,您当前拥有它的方式会崩溃。看起来你试图简单地制作5个可以执行相同操作的相同的字符。
这是我用来尝试完成你所追求的目标的一般策略。由于您的mainPlayer
节点可能是一些复杂的字符,您将重复使用(甚至可能在其他场景中),因此您可以考虑将其放入自己的类中(并将代码放在单独的.swift
文件中)。然后,您可以添加用于移动和执行其他SKAction
s
例如:
import SpriteKit
class Character : SKSpriteNode {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
//setup your node here
self.userInteractionEnabled = true//you need this to detect touches
//log so you know it was created - take this out at some point
print("character created")
}
//create an example action that will move the node to the right by 50
func moveRight() {
print("moving right")
self.runAction(SKAction.moveByX(50, y: 0, duration: 0.1))
}
//you can also override the touch functions so you'll know when the node was touched
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("charater touched")
}
}
然后在你的场景中,当你想创建和使用一个新角色时,你可以这样做:
//create the character
let newPlayer = Character.init(texture: nil, color: UIColor.blueColor(), size: CGSizeMake(50, 50))
//position the character where you want
newPlayer.position = CGPointMake(self.frame.size.width / 2, self.frame.size.height / 2)
//add the character to the scene
self.addChild(newPlayer)
/move the character to the right
newPlayer.moveRight()
让事情变得更多&#34;模块化&#34;这样对于代码的可重用性非常有用。现在,您可以随时随地重用Character
类。即使是在完全不同的游戏中。
在通过一个函数调用使所有字符运行相同的操作方面,我不知道任何允许这样做的事情。虽然您可以通过将所有字符节点放入一个数组并将数组作为参数传递给自定义函数来编写自己的函数,但我个人只是在每个节点上调用moveRight
函数在你实例化它们之后。