我正在为iPhone实现一个轮子,当它被拖到那个方向时应该顺时针或逆时针转动。尽管如此,但平滑度存在一些误差。有时它看起来很混淆它应该转向哪种方式。有什么帮助吗?
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSSet *allTouches = [event allTouches];
int len = [allTouches count]-1;
UITouch *touch =[[allTouches allObjects] objectAtIndex:len];
CGPoint location = [touch locationInView:[self superview]];
xfirst = location.x;
xnext = xfirst;
x = [NSNumber numberWithFloat:xfirst];
yfirst = location.y;
ynext = yfirst;
y = [NSNumber numberWithFloat:yfirst];
//NSLog(@"Touch began for wheel at %f and %f",xfirst, yfirst);
//NSLog(@"Centre %f and %f",self.center.x, self.center.y);
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch =[[allTouches allObjects] objectAtIndex:len];
CGPoint location = [touch locationInView:[self superview]];
xlast = location.x;
ylast = location.y;
//dy / dx (gradient)
if (((ylast-yfirst)/(xlast-xfirst) >= 0.3) || ((ylast-yfirst)/(xlast-xfirst) <= -0.3))
{
int seg1 = [self detectSegment:xnext :ynext];
int seg2 = [self detectSegment:xlast :ylast];
bool direction = [self isClockWise:seg1 :seg2];
lastDirection = direction;
float theAngle = [self getAngle:self.center.x:self.center.y:xfirst:yfirst:xlast:ylast];
theAngle = theAngle / 6;
if (direction == YES)
{
}
else {
theAngle = -1*theAngle;
}
theAngle += totalRadians;
float rads = 6.28318531;
int divAm = 0;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:0];
[formatter setRoundingMode: NSNumberFormatterRoundDown];
float nm = theAngle/rads;
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:nm]];
[formatter release];
divAm = [numberString floatValue];
theAngle = theAngle - (float)(6.28318531*divAm);
totalRadians = theAngle;
xnext = xlast;
ynext = ylast;
[self rotateImage:theAngle];
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
}
-(float) getAngle: (CGFloat)P1x: (CGFloat)P1y: (CGFloat)P2x: (CGFloat)P2y: (CGFloat)P3x: (CGFloat)P3y {
float P23 = [self getLength:P2x:P2y:P3x:P3y];
float P12 = [self getLength:P1x:P1y:P2x:P2y];
float P13 = [self getLength:P1x:P1y:P3x:P3y];
return acos((P23*P23 - P12*P12 - P13*P13)/(-2*P12*P13));
}
-(float) getLength: (CGFloat)P1x: (CGFloat)P1y: (CGFloat)P2x: (CGFloat)P2y
{
return sqrt((P1x-P2x)*(P1x-P2x) + (P1y-P2y)*(P1y-P2y));
}
有什么建议吗?
答案 0 :(得分:2)
我有点困惑为什么你要用这么复杂的算法找到角度。我不明白你为什么需要渐变,在计算中使用数字格式有点奇怪。也就是说,你可能有充分的理由做这些事情,所以我建议你简化算法以测试旋转代码;如果仍然需要,可以在以后添加复杂性。从根本上说,你只需要: -
theAngle = atan2( location.y-self.center.y, location.x-self.center.x )
确保滚轮跟踪你的手指。