2017-01-30 31 views
1

我在Swift中學習了SKNodes,遇到了一個問題。應用程序應該非常簡單:觸摸屏幕並讓節點出現在觸摸位置。我不知道爲什麼,但矩形不斷顯示在屏幕上的不同位置,但sn.positiontouch.location(in: view)的位置相同。怎麼了?SKShpapeNode位置和touch.location差異

import SpriteKit 
import GameplayKit 

class GameScene: SKScene { 

    private var spinnyNode : SKShapeNode? 
    private var touchPoint : CGPoint! 

    override func didMove(to view: SKView) { 

     let size = CGSize(width: 50, height: 50) 

     spinnyNode = SKShapeNode(rectOf: size, cornerRadius: CGFloat(0.6)) //init 

     if let spinnyNode = self.spinnyNode{ 

      spinnyNode.lineWidth = 3 

      let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1)) 
      let fade = SKAction.fadeOut(withDuration: 0.5) 
      let remove = SKAction.removeFromParent() 

      spinnyNode.run(rotate) 
      spinnyNode.run(SKAction.sequence([fade, remove])) 

     } 
    } 

    func touchDown(point pos : CGPoint){ 
     if let sn = self.spinnyNode?.copy() as! SKShapeNode? { 

      sn.position = CGPoint(x: touchPoint.x , y: touchPoint.y) 
      print("touchDown x:\(touchPoint.x), y:\(touchPoint.y)") 

      self.addChild(sn) 
     } 
    } 

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
     guard touches.count == 1 else{ 
      return 
     } 
     if let touch = touches.first{ 
      touchPoint = touch.location(in: view) 

      touchDown(point: touchPoint) 
      print("touchesBegan -> x: \(touchPoint.x) y: \(touchPoint.y)") 
     } 
    } 

回答

0

嘗試做這樣的

import SpriteKit 
import GameplayKit 

class GameScene: SKScene { 

//use whichever image for your node 
var ballNode = SKSpriteNode(imageNamed: "ball") 

var fingerLocation = CGPoint() 

override func didMove(to view: SKView) { 

    ballNode.size = CGSize(width: 100, height: 100) 
    ballNode.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.5) 

} 


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


    if let location = touches.first?.location(in: self){ 

     if let copy = ballNode.copy() as? SKSpriteNode { 
      copy.position = location 
      addChild(copy) 
     } 
    } 
} 

} 

東西我每次點擊一個隨機點,出現球。希望這可以幫助。

+0

當我嘗試這個我觸摸的位置和skspritenode位置設置在不同的位置。例如。當我觸摸點是(10,-20)時,skspritenode找到不同的位置。當我點擊那個位置不同的節點時。如何解決這個問題。我的需要是當我點擊單點位置sksprite節點定位在該點上 – Araf