2016-12-05 29 views
1

,找不到一個「基本解決」我的問題雪碧不會隨手指移動/ SpriteKit /斯威夫特3

您好,我想創建一個簡單的SKSpriteNode,將移動隨着我的手指在屏幕上的任何地方(x & y coords)。到目前爲止,我所做的是下面的代碼,我似乎無法找到其他的東西,因爲我的Sprite在遊戲運行時甚至不會移動。我也遇到了一個錯誤:

simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode 

這行代碼導致我的程序不能運行,因爲我已經添加它。請並且感謝您的幫助。

在這種情況下,Sprite「simpleS」是我嘗試在觸摸開始時移動的Sprite。

代碼從這裏開始:

import SpriteKit 
    import GameplayKit 

    class GameScene: SKScene { 

var simpleS = SKSpriteNode() 

override func didMove(to view: SKView) { 

    simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode 

    simpleS.physicsBody?.affectedByGravity = true 
} 



override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 

    for touch in touches { 
     let location = touch.location(in: self) 

     simpleS.run(SKAction.moveTo(x: location.x, duration: 0.0)) 
     simpleS.run(SKAction.moveTo(y: location.y, duration: 0.0)) 

    } 

} 
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { 

    for touch in touches { 
     let location = touch.location(in: self) 

     simpleS.run(SKAction.moveTo(x: location.x, duration: 0.0)) 
     simpleS.run(SKAction.moveTo(y: location.y, duration: 0.0)) 

    } 
     } 
    } 
+0

此代碼有幾個問題。嘗試按照這樣的指南來獲得更多SpriteKit的速度; https://www.raywenderlich.com/49721/how-to-create-a-breakout-game-using-spritekit。 –

回答

0

這個代碼

simpleS = self.childNode(withName: "simpleS") as! SKSpriteNode 

在GameScene.sks與GameScene.swift 所以你必須第一步連接精靈確保你在sks文件中設置了正確的名字(確切地說是「simpleS」)。

如果您做得對,請將錯誤發送給我們。 我已經構建並運行了您的代碼,並且所有工作都以正確的方式進行。

另一點是,如果你想讓你的精靈只通過你的手指移動而移動,你必須刪除touchesBegan函數中的代碼,因爲touchesBegan會在你觸摸的任何地方移動你的精靈。

+0

https://gyazo.com/a499ed44c710c13895ee0800ed8754f0這是我得到的錯誤,太奇怪了。不知道我做錯了什麼,謝謝你的幫助。 –

+1

沒關係,我搞定了!原來,我將背景命名爲「simpleS」,而不是實際的節點......無論如何感謝您的幫助! –