ios - 将对象移动到特定区域

标签 ios iphone xcode swift drag-and-drop

我在 View 中有一个名为 circle 的圆和一条名为 ground 的线。

enter image description here

我可以在整个 View 中拖动和移动圆圈,但是当我尝试限制它(在代码中)仅在地面区域下移动时 - 它有效(当我尝试将其拖动到地面上方时)并且圆圈仅通过我的 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)
        }
    }

最佳答案

我已经解决了:

touchesMoved 函数中我编写了以下代码:

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

关于ios - 将对象移动到特定区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33340690/

相关文章:

ios - 错误 ITMS-90514 : "Missing Code Signing Entitlement. Use of the ' network-authentication' background mode in 'Payload/xxx.app/xxx'

ios - 如何在 iOS/xcode 中重用颜色和样式?

ios - 如何在测试期间应用程序初始化之前清除 IOS 钥匙串(keychain)

ios - 将 UIView 添加到 TableViewfooter 不完全可见

ios - 将 AVAudioRecorder 转换为 NSString 或 bytes

iphone - 在 iPhone 应用程序中保存对象数组的最佳方式。

iphone - 如果用户移动太快,UIPageViewController View 会困惑

ios - 文件夹 "Images.xcassets"不存在

objective-c - 为什么 UIAlertView dismissAnimated : work at all?

ios - 在项目中导航