ios - 操纵杆,将控制杆夹在操纵杆底座内

标签 ios swift sprite-kit touch joystick

我有一个在 SpriteKit 中创建的圆形操纵杆,我如何将较小的控制杆夹在较大的操纵杆底座内,并以编程方式防止它超出操纵杆底座。

在我的 didMove(toView:) 方法中设置操纵杆的代码。

var DPad = SKSpriteNode(imageNamed: "dpad")
DPad.size = CGSize(width: 150, height: 150)
DPad.position = CGPoint(x: -270, y: -100)

var thumbNode = SKSpriteNode(imageNamed: "joystick")
thumbNode.size = CGSize(width: 50, height: 50)
thumbNode.position = CGPoint(x: DPad.position.x, y: DPad.position.y)

touchesBegan 方法

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if thumbNode.contains(location) && isTracking == false {
            isTracking = true
        }

    }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        if isTracking == true {
            thumbNode.run(SKAction.move(to: location, duration: 0.01))
        }
    }
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        thumbNode.run(SKAction.move(to: DPad.position, duration: 0.01))
        if thumbNode.position.x > DPad.size.width || thumbNode.position.y > DPad.size.height {
            thumbNode.position = DPad.position
        }
    }
}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    if thumbNode.physicsBody?.velocity.dx > Float(0) || thumbNode.physicsBody?.velocity.dx < Float(0) {
        print("greater")
    }
}

最佳答案

为此,您可以使用 SKConstraint.distance(SKRange(upperLimit: radius), to: baseNode)

要添加它,只需执行 joystickNode.constraints = [SKConstraint.distance(SKRange(upperLimit: radius), to: baseNode)]

关于ios - 操纵杆,将控制杆夹在操纵杆底座内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47040911/

相关文章:

ios - 通过 Unwind Segues 发送数据

ios - 在远程通知上打开正确的消息线程 - 带解析的 iOS Swift Chat 应用程序

swift : Custom operator to update dictionary value

swift - 如何在 tableView 的特定单元格中仅执行一次代码(在 dequeueReusableCell 下)

ios - 场景前 SKView 闪烁灰色

ios - SpriteKit 背景音乐不会永远循环

ios - 如何用单个表格部分显示不同的 View ?

iphone - 更新父 View Controller 的数据源

iOS10 : German Localization not working

ios - 使用 SKPhysicsBody 方法复制自定义 SKAction 螺旋运动