我正在使用swift和库SpriteKit创建一个Snake Game。
在程序的顶部,我声明了一个变量
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var player = SKSpriteNode(imageNamed: "head")
[...]
}
这样,我可以在所有函数中访问此变量。但是我想在蛇移动时改变它的形象。例如,如果蛇向上移动,我想显示蛇向上看的图像。
所以我有这段代码来控制蛇的运动
if movesController[0]==true{
playerY += 56.0000000
}
if movesController[1]==true{
playerY -= 56.0000000
}
if movesController[2]==true{
playerX += 56.0000000
}
if movesController[3]==true{
playerX -= 56.0000000
}
并且要改变蛇的形象,我以为我可以做到这一点
if movesController[0]==true{
playerY += 56.0000000
player = SKSpriteNode(imageNamed: "head_up")
}
if movesController[1]==true{
playerY -= 56.0000000
player = SKSpriteNode(imageNamed: "head_down")
}
if movesController[2]==true{
playerX += 56.0000000
player = SKSpriteNode(imageNamed: "head_right")
}
if movesController[3]==true{
playerX -= 56.0000000
player = SKSpriteNode(imageNamed: "head_left")
}
但是加上这4行,Snake无法移动...因此,我尝试更改player
变量的声明
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var imageName = "head"
var player = SKSpriteNode(imageNamed: "\("imageName)")
[...]
}
然后用imageName = "move_up"
更改我之前添加的4行(或向下-左-右)
但是在程序开始时,它给了我一个错误
Cannot use instance member 'imageName' within property initializer; property initializers run before 'self' is available
我该怎么办?我的最后一个选择是创建另一个playerVariable
并将其放置在真实的蛇图像上方,但这将意味着添加更多节点而没有任何事情。
实际上,您解决此问题的方法是正确的。将self放在imageName变量之前。会的。
import SpriteKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var imageName = "head"
var player = SKSpriteNode(imageNamed: "\("self.imageName)")
[...]
}
您必须更改播放器的纹理,但不要在每个步骤中都创建新的播放器。尝试添加此功能:
func changeHead(imageNamed name: String){
player.texture = SKTexture(imageNamed: name)
}
并且程序文本将以这种方式更改:
if movesController[0]==true{
playerY += 56.0000000
changeHead(imageNamed: "head_up")
}
if movesController[1]==true{
playerY -= 56.0000000
changeHead(imageNamed: "head_down")
}
if movesController[2]==true{
playerX += 56.0000000
changeHead(imageNamed: "head_right")
}
if movesController[3]==true{
playerX -= 56.0000000
changeHead(imageNamed: "head_left")
}