2015-10-26 66 views
0

我在視圖中有一個名爲circle的圓和一條名爲ground的線。在特定區域中移動對象

enter image description here

我可以拖動&移動的全貌了一圈,但是當我試圖對其進行限制(代碼),只在地面區域移動 - 它的工作原理(當我嘗試將它拖到高於地面),而圓只是通過我的x位置拖動來移動,但是當我嘗試將它拖回地下時 - 圓只通過拖動x位置並且y位置拖動不會改變(y是地面y)。

我怎樣才能讓它以一種自由的方式在地面下而不僅僅是拖動的x位置再次移動? 這裏是我試過到目前爲止:

let ground = SKSpriteNode() 
    var circle = SKShapeNode(circleOfRadius: 40) 

    override func didMoveToView(view: SKView) { 
     /* Setup your scene here */ 

//  ground.physicsBody?.dynamic = false 
     ground.color = SKColor.redColor() 
     ground.size = CGSizeMake(self.frame.size.width, 5) 
     ground.position = CGPoint(x: CGRectGetMidX(self.frame), y: self.frame.size.height/5) 

     self.addChild(ground) 

     circle.position = CGPointMake(CGRectGetMidX(self.frame) ,CGRectGetMinY(ground.frame) - (circle.frame.size.height/2)) 
     circle.strokeColor = SKColor.blackColor() 
     circle.glowWidth = 1.0 
     circle.fillColor = SKColor.orangeColor() 

     self.addChild(circle) 

    } 
    var lastTouch: CGPoint? = nil 
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     /* Called when a touch begins */ 
    let touch = touches.first 
    let touchLocation = touch!.locationInNode(self) 
     if circle.position.y < ground.position.y - (circle.frame.size.height/2){ 
      circle.position = touchLocation 
     } else { 
      circle.position.x = CGFloat(touchLocation.x) 
     } 
    } 
    override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 
     let touch = touches.first 
     let touchLocation = touch!.locationInNode(self) 
     if circle.position.y < ground.position.y - (circle.frame.size.height/2) { 
      circle.position = touchLocation 
     } else { 
      circle.position.x = CGFloat(touchLocation.x) 
     } 
    } 

回答

0

我已經解決了它:

touchesMoved FUNC我寫了這個代碼:

for touch in touches { 
      if touchLocation.y < ground.position.y { 
       circle.position = touchLocation 
      } else { 
       circle.position.x = touchLocation.x 
      } 
     } 
相關問題