所以基本上,我有sprite kit游戏杆实现。一切正常,除非涉及顶部和底部。基本上,当使用操纵杆绕拐角移动时,它会像在正方形中一样溢出。我知道问题出在我的 moveJoystick()函数的最后else语句位置操作中,但无法解决。这是我的下课:
class LiveControllerJoystick: SKNode {
var joyStick = SKShapeNode()
var stick = SKShapeNode()
var joyStickPath: UIBezierPath!
var maxRange : CGFloat!
var baseRadius : CGFloat!
let xValue : CGFloat = 0
let yValue : CGFloat = 0
var blockedX: Bool!
var blockedY: Bool!
var joyStickAction : ((_ x: CGFloat, _ y: CGFloat) -> ())?
init(frame: CGRect) {
// Dynamic Coordinates for SKView
maxRange = frame.size.width / 3
baseRadius = frame.size.width / 3
let joyStickRect = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
joyStickPath = UIBezierPath(ovalIn: joyStickRect)
joyStick = SKShapeNode(path: joyStickPath.cgPath,centered: true)
joyStick.strokeColor = UIColor.clear
let stickRect = CGRect(x: 0, y: 0, width: frame.size.height / 3, height: frame.size.height / 3)
let stickPath = UIBezierPath(ovalIn: stickRect)
stick = SKShapeNode(path: stickPath.cgPath,centered: true)
stick.strokeColor = UIColor.clear
stick.lineWidth = 4
super.init()
stick.fillColor = hexStringToUIColor(hex: "#2D2D2D")
joyStick.fillColor = hexStringToUIColor(hex: "#830B2C")
addChild(joyStick)
addChild(stick)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MOve Joystick Up,Down,Left,Right
func moveJoystick(touch: UITouch){
let p = touch.location(in: self)
let radius = min(baseRadius,sqrt(pow(p.y, 2) + pow(p.x, 2)))
var angle = atan2(p.y, p.x)
angle = (angle * 2 / CGFloat.pi).rounded() * (CGFloat.pi / 2)
if((blockedY == true && blockedX == true) || (blockedX == true && blockedY == true)){
stick.position = CGPoint(x: 0, y: 0)
}
else if(blockedY == true){
stick.position = CGPoint(x: cos(angle) * radius, y: 0)
}
else if(blockedX == true){
stick.position = CGPoint(x: 0, y: sin(angle) * radius)
}
else{
let x = p.x.clamped(-maxRange, maxRange)
let y = p.y.clamped(-maxRange, maxRange)
stick.position = CGPoint(x: x, y: y)
}
let xValue = cos(angle) * radius
let yValue = sin(angle) * radius
if let joyStickAction = joyStickAction {
joyStickAction(xValue,yValue)
}
}
func hexStringToUIColor (hex:String) -> UIColor {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
return UIColor.gray
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
return UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
// Return min max value
extension CGFloat {
func clamped(_ v1: CGFloat,_ v2: CGFloat) -> CGFloat {
let min = v1 < v2 ? v1 : v2
let max = v1 > v2 ? v1 : v2
return self < min ? min : (self > max ? max : self)
}
}
任何帮助或提示,我们将不胜感激。预先感谢。