تساعد في حساب ATAN2 بشكل صحيح
-
28-09-2019 - |
سؤال
أحتاج إلى حساب الزاوية بين الخطوط. أحتاج إلى حساب atan. لذلك أنا أستخدم مثل هذا الرمز
static inline CGFloat angleBetweenLinesInRadians2(CGPoint line1Start, CGPoint line1End)
{
CGFloat dx = 0, dy = 0;
dx = line1End.x - line1Start.x;
dy = line1End.y - line1Start.y;
NSLog(@"\ndx = %f\ndy = %f", dx, dy);
CGFloat rads = fabs(atan2(dy, dx));
return rads;
}
لكن لا يمكنني الحصول على أكثر من 180 درجة ((بعد 179 درجة يسير 178..160..150 وما إلى ذلك.
أحتاج إلى التدوير على 360 درجة. كيف يمكنني فعل ذلك؟ ما هو الخطأ؟
مابي هذا يساعد:
//Tells the receiver when one or more fingers associated with an event move within a view or window.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSArray *Touches = [touches allObjects];
UITouch *first = [Touches objectAtIndex:0];
CGPoint b = [first previousLocationInView:[self imgView]]; //prewious position
CGPoint c = [first locationInView:[self imgView]]; //current position
CGFloat rad1 = angleBetweenLinesInRadians2(center, b); //first angel
CGFloat rad2 = angleBetweenLinesInRadians2(center, c); //second angel
CGFloat radAngle = fabs(rad2 - rad1); //angel between two lines
if (tempCount <= gradus)
{
[imgView setTransform: CGAffineTransformRotate([imgView transform], radAngle)];
tempCount += radAngle;
}
}
المحلول
مسح ال fabs
استدعاء وجعلها ببساطة:
CGFloat rads = atan2(dy, dx);
نصائح أخرى
atan2
النتائج العوائد في [-180،180] (OR -PI ، PI في Radians). للحصول على نتائج من 0،360 الاستخدام:
float radians = atan2(dy, dx);
if (radians < 0) {
radians += M_PI*2.0f;
}
تجدر الإشارة إلى أنه من المعتاد التعبير عن الدورات في [-PI ، PI] وبالتالي يمكنك فقط استخدام نتيجة atan2
دون القلق بشأن العلامة.
استخدم هذه الوظيفة في Swift. هذا يتأكد من أن الزاوية من "Frompoint" إلى "Topoint" تهبط بين 0 إلى <360 (لا تشمل 360). يرجى ملاحظة أن الوظيفة التالية تفترض أن CGPointzero في الزاوية اليسرى العلوية.
func getAngle(fromPoint: CGPoint, toPoint: CGPoint) -> CGFloat {
let dx: CGFloat = fromPoint.x - toPoint.x
let dy: CGFloat = fromPoint.y - toPoint.y
let twoPi: CGFloat = 2 * CGFloat(M_PI)
let radians: CGFloat = (atan2(dy, -dx) + twoPi) % twoPi
return radians * 360 / twoPi
}
للحالة التي يكون فيها الأصل في الركن الأيسر السفلي
let twoPi = 2 * Float(M_PI)
let radians = (atan2(-dy, -dx) + twoPi) % twoPi
let angle = radians * 360 / twoPi