aide à calculer correctement atan2
-
28-09-2019 - |
Question
Je dois calculer l'angle entre les lignes. Je dois calculer atan. Donc, je suis en utilisant ce code
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;
}
Mais je ne peux pas obtenir plus de 180 degrés ((après 179 ° va 178..160..150 et ainsi de suite.
Je dois tourner sur 360 degrés. Comment puis-je le faire? Quel est le problème?
Maby cette aide:
//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;
}
}
La solution
Supprimer l'appel fabs
et faire simplement:
CGFloat rads = atan2(dy, dx);
Autres conseils
renvoie des résultats dans atan2
[-180180] (ou -pi, pi en radians). Pour obtenir des résultats de 0360 utilisation:
float radians = atan2(dy, dx);
if (radians < 0) {
radians += M_PI*2.0f;
}
Il convient de noter qu'il est typique d'exprimer des rotations dans [-pi, pi] et vous pouvez thusly il suffit d'utiliser le résultat de atan2
sans se soucier du signe.
Utilisez cette fonction Swift. Cela fait que l'angle de « fromPoint » terres « toPoint » entre 0 à <360 (non compris 360). S'il vous plaît noter, la fonction suivante suppose que CGPointZero est dans le coin supérieur gauche.
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
}
Pour le cas où l'origine est dans le coin inférieur gauche
let twoPi = 2 * Float(M_PI)
let radians = (atan2(-dy, -dx) + twoPi) % twoPi
let angle = radians * 360 / twoPi