2015-10-26 63 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 
      } 
     } 
相关问题