I'm using an NSTimer to animate an array of objects across the screen. Currently they move from left to right. However, I would like them to move in a circular fashion instead. How can I do this?
scrollItems = [NSTimer scheduledTimerWithTimeInterval:1.0/30.0
开发者_StackOverflow target:self
selector:@selector(scrollItems)
userInfo:nil
repeats:YES];
- (void)scrollItems {
for (UIImageView *anItem in itemsArray) {
CGRect oldFrame = anItem.frame;
anItem.frame = CGRectMake(oldFrame.origin.x+5, oldFrame.origin.y, oldFrame.size.width, oldFrame.size.height);
}
}
When I say circular fashion, I mean as if they were following the circumference of a circle. Thanks!
Basically the same way -- think you need to bust out the trigonometry.
http://en.wikipedia.org/wiki/Trigonometry
Right now you're just adding five to x to make it move. Instead you need to calculate a new x AND y based on sin cos and crap like that and some sort of counter to tell it where on the circle it should be.
Update: The unit circle might help too.
So at any time on the clock your object should be at some point on this circle, correct? So you have to go from time -> angle -> x & y coordinate on the circle. Working backwards, you can get an x y coordinate on the circle if you have an angle (a number between 0 and 360 degrees) -- that's the unit circle link.
So you need an angle. That angle will be a function of time, right? So at time 0 you could say that's an angle of 0, and then you know where on the circle you should be based on the formulas in the above links. At time 1, it could be an angle of 1, etc. Keep doing that over time and you're drawing a circle. You just need to figure out how to translate time into a number between 0-360. That function will determine the speed at which your object moves.
So basically you need something that can use time to calculate an x y. After that's working you could get clever and have that function also take in speed, center, and radius and return an x y based on those things. Up to you.
Sorry I don't have time to write this code, but it should be pretty do-able.
精彩评论