在特定区域中移动对象

时间:2015-10-26 07:39:54

标签: ios iphone xcode swift drag-and-drop

我在视图中有一个名为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)
        }
    }

1 个答案:

答案 0 :(得分:0)

我已经解决了它:

touchesMoved func中我写了这段代码:

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