2017-01-25 48 views
1

該代碼將返回x1和y1值,但似乎沒有通過touchesEnded函數運行。我的目標是創建一個矩形,從用戶觸摸的角落開始,並在用戶舉起手指的地方結束。爲什麼我的touchesEnded函數沒有初始化?

  //touch initialized 
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
      for touch in touches { 
      let location = touch.location(in: self) 
      let x1 = location.x 
      let y1 = location.y 
      print(x1,y1) 

     } 

      func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){ 
      for touch in touches{ 

      let location2 = touch.location(in: self) 
      let x2 = location2.x 
      let y2 = location2.y 
      let originX = min(x1,x2) 
      let originY = min(y1,y2) 
      let cornerX = max(x1,x2) 
      let cornerY = max(y1,y2) 
      let boxWidth = cornerX - originX 
      let boxHeight = cornerY - originY 

      let box = SKSpriteNode() 
      box.size = CGSize(width: boxWidth, height: boxHeight) 
      box.color = SKColor.black 
      box.position = CGPoint(x:originX, y: originY) 
      addChild(box) 

      print(x1,y1,x2,y2) 
      } 
      } 
+0

我認爲你需要重寫'touchesEnded'功能像你這樣'touchesBegan' – ronatory

+0

使touchesEnded函數成爲一個覆蓋函數會給我一個錯誤「'override'只能在類成員上指定」。 – nowBrain

+0

@nowBrain我的答案解決了問題嗎?如果是這樣,你可以請標記爲正確 – Nik

回答

2

在你的代碼的問題是,它缺少一個大括號關閉touchesBegan,所以touchesEnded是不允許被覆蓋,因爲它在技術上你touchesBegan而非場景本身。

試試這個:

var x1: CGFloat = 0.0 
var y1: CGFloat = 0.0 

//... 

//touch initialized 
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { 
    for touch in touches { 
     let location = touch.location(in: self) 
     x1 = location.x 
     y1 = location.y 
     print(x1,y1) 
    } 
} 

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

    for touch in touches{ 
     let location2 = touch.location(in: self) 
     let x2 = location2.x 
     let y2 = location2.y 
     let originX = min(x1,x2) 
     let originY = min(y1,y2) 
     let cornerX = max(x1,x2) 
     let cornerY = max(y1,y2) 
     let boxWidth = cornerX - originX 
     let boxHeight = cornerY - originY 
     let box = SKSpriteNode() 
     box.size = CGSize(width: boxWidth, height: boxHeight) 
     box.color = SKColor.black 
     box.position = CGPoint(x:originX, y: originY) 
     addChild(box) 

     print(x1,y1,x2,y2) 
    } 
} 

當然,而不是保存每個x和y座標分別,我想突出部分儲存2個CGPoints

+0

當我這樣做時,我得到錯誤「使用未解析的標識符'x1'」。那麼,我不能將信息從一個功能存儲到另一個功能嗎? – nowBrain

+0

@nowBrain我更新了答案 – Nik

相關問題