Search code examples
iosswiftsprite-kittouchjoystick

Joystick, clamping the control stick inside the joystick base


I have a circular joystick i created in SpriteKit, how do i clamp the smaller control stick inside of the larger joystick base and prevent it from going outside the joystick base programmatically.

The code setting up my joystick inside of my didMove(toView:) method.

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 methods

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")
    }
}

Solution

  • For this, you can use SKConstraint.distance(SKRange(upperLimit: radius), to: baseNode)

    To add it, just do joystickNode.constraints = [SKConstraint.distance(SKRange(upperLimit: radius), to: baseNode)]