如何在精灵工具包中的动作中运行函数?



我正在制作的游戏有以下代码。在其中一个部分中,我有

let spawn = SKAction.run {
self.createCars()
}

但是由于某种原因,我不断收到一个错误,说"类型值'(NSObject -> () -> GameScene'没有成员'createCars',即使createCars是在我的代码中定义较低的函数。为什么会发生这种情况,我该怎么做才能解决这个问题?

import SpriteKit
import GameplayKit
class GameScene: SKScene, SKPhysicsContactDelegate {
var lanecounter:CGFloat = 0
var score:Int = 0
var player:SKSpriteNode?
let scoreLabel = SKLabelNode()
let highScoreLabel = SKLabelNode()
var direction:Int?
let noCategory:UInt32 = 0
let carCategory:UInt32 = 0b1
let playerCategory:UInt32 = 0b1 << 1
let pointCategory:UInt32 = 0b1 << 2
var died:Bool?
var restartBTN = SKSpriteNode()
let moveLeft:SKAction = SKAction.moveBy(x: -100, y: 0, duration: 0.065)
let moveRight:SKAction = SKAction.moveBy(x: 100, y: 0, duration: 0.065)
let moveDown:SKAction = SKAction.moveTo(y: -800, duration: 1.1)
let spawn = SKAction.run {
self.createCars()
}
let delay = SKAction.wait(forDuration: 4)
func createCars(){
let middlePoints = SKSpriteNode()
var openLane:CGFloat = 0
middlePoints.size = CGSize(width: 100, height: 10)
middlePoints.physicsBody = SKPhysicsBody(rectangleOf: middlePoints.size)
//middlePoints.color = SKColor.purple
middlePoints.physicsBody?.categoryBitMask = pointCategory
middlePoints.physicsBody?.collisionBitMask = playerCategory
middlePoints.physicsBody?.contactTestBitMask = playerCategory
var randInt:Int = 0
randInt = Int(arc4random_uniform(3))
if lanecounter == -2 {
if randInt == 0 || randInt == 1 {
openLane = -1
}
if randInt == 2 {
openLane = -2
}
}
if lanecounter == 2 {
if randInt == 0 || randInt == 1 {
openLane = 1
}
if randInt == 2 {
openLane = 2
}
}
if lanecounter == -1 || lanecounter == 0 || lanecounter == 1 {
if randInt == 0 {
openLane = lanecounter - 1
}
if randInt == 1 {
openLane = lanecounter
}
if randInt == 2 {
openLane = lanecounter + 1
}
}
//print("lanecounter is", lanecounter)
//print("open lane is", openLane)
if openLane != -2 {
spawnCar(xCord: -2)
}
if openLane != -1 {
spawnCar(xCord: -1)
}
if openLane != 0 {
spawnCar(xCord: 0)
}
if openLane != 1 {
spawnCar(xCord: 1)
}
if openLane != 2 {
spawnCar(xCord: 2)
}
middlePoints.position = CGPoint(x: (openLane*100), y: self.frame.height)
self.addChild(middlePoints)
middlePoints.run(moveDown)
}
}

最小、完整且可验证

首先,我们需要一个最小、完整和可验证的示例,如下所示:

class GameScene: SKScene {
let spawn = SKAction.run {
self.createCars()
}
func createCars() { }
}

错误:类型"(NSObject) -> () -> GameScene"的值没有成员"createCars">

问题

发生此问题是因为您无法在使用self定义的同一行上填充属性(事实上self尚不存在)。

溶液

但是,您可以使用惰性属性,该属性仅在调用时进行评估(届时self将可用)。

class GameScene: SKScene {
lazy var spawn: SKAction = {
SKAction.run { self.createCars() }
}()
func createCars() { }
}

最新更新