我在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)

接触开始方法
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)]

10-08 05:35