Drag Ball über Kreisweg in Swift
Ich habe einen Kreispfad erstellt, der Mittelpunkt des Kreispfads befindet sich in der Mitte der Ansicht. Dann habe ich einen Ball gemacht, der sich nur auf der Kreisbahn bewegen kann (zumindest möchte ich, dass er so ist):
Ich habe eine Funktion erstellt, die den Ball dorthin bewegt, wo ich ihn ziehe (nur auf dem Kreisweg), aber aus irgendeinem Grund wird er verrückt, wenn ich ihn ziehe, und bewegt sich nicht so, wie ich es möchte.
Dies ist mein Code bisher:
class ViewController: UIViewController {
var midViewX = CGFloat()
var midViewY = CGFloat()
var circlePath2 = UIBezierPath()
var shapeLayer2 = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
midViewX = view.frame.midX
midViewY = view.frame.midY
// Do any additional setup after loading the view, typically from a nib.
let circlePath = UIBezierPath(arcCenter: CGPoint(x: midViewX,y: midViewY), radius: CGFloat(100), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = UIColor.redColor().CGColor
shapeLayer.lineWidth = 3.0
view.layer.addSublayer(shapeLayer)
var angleEarth: Double = 180
var angleEarthAfterCalculate: CGFloat = CGFloat(angleEarth*M_PI/180) - CGFloat(M_PI/2)
var earthX = midViewX + cos(angleEarthAfterCalculate)*100
var earthY = midViewY + sin(angleEarthAfterCalculate)*100
circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX,y: earthY), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
shapeLayer2.path = circlePath2.CGPath
shapeLayer2.fillColor = UIColor.blueColor().CGColor
shapeLayer2.strokeColor = UIColor.clearColor().CGColor
shapeLayer2.lineWidth = 7
view.layer.addSublayer(shapeLayer2)
let dragBall = UIPanGestureRecognizer(target: self, action:#selector(ViewController.dragBall(_:)))
view.addGestureRecognizer(dragBall)
}
@IBAction func dragBall(recognizer: UIPanGestureRecognizer) {
let point = recognizer.locationInView(self.view);
let earthX = Double(point.x)
let earthY = Double(point.y)
let midViewXDouble = Double(midViewX)
let midViewYDouble = Double(midViewY)
let angleX = (earthX - midViewXDouble)
let angleY = (earthY - midViewYDouble)
let angle = tan(angleY/angleX)
let earthX2 = midViewXDouble + cos(angle)*100
let earthY2 = midViewYDouble + sin(angle)*100
circlePath2 = UIBezierPath(arcCenter: CGPoint(x: earthX2,y: earthY2), radius: CGFloat(10), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
shapeLayer2.path = circlePath2.CGPath
}
}
Die Lösung ist wahrscheinlich in der Mathematik, die ich in der @ gemacht ha dragBall Func