从另一个类创建对象时,对象不会生成



所以,它几乎是这样的:我有这个可以工作的点击手势识别器,这是GameView控制器类中的代码:

@IBAction func handleTap(_ sender: UITapGestureRecognizer) 
{
GameScene().makeCirc();
}

我调用的函数在 GameScene 类中,它看起来像这样:

public func makeCirc() {
circle = SKShapeNode (circleOfRadius: 15)
circle.name = "white circ"
circle.position = CGPoint (x: 0, y: 10)
circle.fillColor = .white
circle.physicsBody = SKPhysicsBody(circleOfRadius: 15)
circle.physicsBody?.isDynamic = true
circle.physicsBody?.affectedByGravity = false
circle.physicsBody?.linearDamping = 0
circle.physicsBody?.restitution = 1.0
circle.physicsBody?.allowsRotation = true
circle.physicsBody?.mass = 300
circle.physicsBody?.density = 2*3.14*15/(circle.physicsBody?.mass)!
circle.physicsBody?.angularDamping = 0.0
self.addChild(circle)
circle.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy:1.0))
print(circCount)
circCount += 1
}

我在更新功能上还有一个计时器,以便每隔一段时间就会生成一个球。当我点击屏幕时,球也必须生成。这是代码:

override func update(_ currentTime: TimeInterval)
{
timer += 1
if timer > spawntime {
makeCirc()
timer = 0
}
if circCount > 0 {
if (self.childNode(withName: "white circ")?.position.y)! > self.frame.maxY - 100 {
self.childNode(withName: "white circ")?.removeFromParent()
circCount -= 1
}
}
}

但是,输出有点奇怪。如果不点击,输出是 circCount,它通常是一个常数 12,这是它应该的样子。但是,当我点击时,显示的 circCount 为 0,而不是生成球并使 circCount 13+,但是,所有对象仍在屏幕上。

有没有办法从另一个职业生成球而没有 circCount 为 0?谢谢!


编辑:这是viewDidMove功能,如果它有帮助:

override func viewDidLoad() {
super.viewDidLoad()
// Load 'GameScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
self.view.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleTap(_:)))
self.view.addGestureRecognizer(tapGesture)
if let scene = GKScene(fileNamed: "GameScene") {
// Get the SKScene from the loaded GKScene
if let sceneNode = scene.rootNode as! GameScene? {
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFill
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
}

好的,所以我在完成下面所做的工作后就让它工作了。感谢您的帮助!

let scene = GKScene (fileNamed: "GameScene")
var instance = GameScene()
override func viewDidLoad() {
super.viewDidLoad()
let sceneNode = scene?.rootNode as! GameScene?
// Load 'GameScene.sks' as a GKScene. This provides gameplay related content
// including entities and graphs.
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleTap(_:)))
self.view.addGestureRecognizer(tapGesture)
self.view.isUserInteractionEnabled = true
// Get the SKScene from the loaded GKScene
// Set the scale mode to scale to fit the window
sceneNode?.scaleMode = .aspectFill
instance = (sceneNode)!
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true

}
}

相关内容