0

I'm facing a strange issue on CAKeyFrameAnimation.

Here's the code:

//Inside the selector method of the button
CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"position"];
[anim setDelegate:self];
anim.path = racetrack.path;
anim.rotationMode = kCAAnimationRotateAuto;
anim.repeatCount = 0;
anim.duration = 10.0;

[carBtn.layer addAnimation:anim forKey:@"race"];

The animation works fine. The problem occurs when the carBtn (a button with a car background image) is pressed. The button's image rotate by 180° for no reason (at least no reason for me). I've to rotate the button myself with this line of code after the creation of the animation

carBtn.transform = CGAffineTransformMakeRotation(M_PI);

...but for a second or two (before the animation starts) the car is faced opposite to its initial position. The button is created in this way:

UIImage* car = [UIImage imageNamed:@"car_image"];
carBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[carBtn setFrame:CGRectMake(startPoint.x-45, startPoint.y-33, macchina.size.width, macchina.size.height)];
[carBtn setBackgroundImage:car forState:UIControlStateNormal];
[carBtn setBackgroundImage:car forState:UIControlStateHighlighted];
[carBtn addTarget:self action:@selector(carPressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:carBtn];

How could this be possible? Thanks

Niccolò Passolunghi
  • 5,608
  • 2
  • 24
  • 33

1 Answers1

0

This is how it works: the X axis of your view is aligned along the tangent of your path.

If the rotation you apply explicitly works for you, I would stick with that. Otherwise you will find a fully worked out solution here.

Community
  • 1
  • 1
sergio
  • 67,961
  • 11
  • 98
  • 119
  • Thanks for the help. Unfortunately in my case the solution you linked doesn't work. I tried to use the Caleb's"animate" method but the duration of UIView animationWithDuration block is not working. The car moves around the path in less then 1 sec although I've set the duration to 10sec. Any suggestions about this issue? – Niccolò Passolunghi Feb 10 '13 at 19:10
  • I thought that the problem was the direction of my path which goes along the negative x coordinate. So I create the inverse path with the first movement along the positive x coordinate. But the problem remains. The button (or image) rotate by 180° just before the animation starts. Frustrating! – Niccolò Passolunghi Feb 10 '13 at 20:41