I am making a game that contains a virtual joystick. My joystick is composed by two SKSpriteNode
, one for the stick the other for the base panel. ( see the picture below )
Obviously my joystick can only be moved following the green semi-circle on the panel.
My problem here is that i'm trying to make it happen, here is my code for now:
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
guard isTracking else {
return
}
let maxDistantion = panel.radius
let realDistantion = sqrt(pow(location.x, 2) + pow(location.y, 2))
let needPosition = realDistantion <= maxDistantion ? CGPoint(x: location.x, y: location.y) : CGPoint(x: location.x / realDistantion * maxDistantion, y: location.y / realDistantion * maxDistantion)
if (needPosition.y > 0) {
stick.position = needPosition
} else {
stick.position = CGPoint(x: needPosition.x, y: 0)
}
data = AnalogJoystickData(velocity: needPosition, angular: -atan2(needPosition.x, needPosition.y))
}
}
With this code, I can move into the semi-circle, but I would to only move my stick onto the green line, if someone can help me with my poor mathematics
Thank you