How to create a moving balls application in iPhone
I want to c开发者_开发百科reate an application where balls keep moving on iPhone screen and they when they collide they gets a rebounding action. Every minute I want to add 1 balll upto a limit.
Is there any easy way to do it or anyone have done this kind of application.
I coded something like this up as an exercise a few months back. I was using around 120 facets on each sphere and very standard completely elastic 'billiard ball' collision physics - implemented directly in OpenGL using Phong shading.
I don't pretend the application was optimised but there wasn't any utter howlers in it, and on a standard iPhone (3G, not the latest 3GS ones) I was able to handle about a dozen balls before the frame-rate slowed to unusable.
Kind of an open-ended question but here is a tutorial on creating "pong" which should get you started thinking about the physics behind the motion.
Split up your app into lots of smaller problems. Start by displaying one square, then make it a sphere, then try displaying many of them, and then adding some movement, and then the physics calculations. There are probably lots of tutorials on each of those smaller steps.
Hope this lines of code may helps you.
Declare this in your .h file:
IBOutlet UIImageView *ball;
CGPoint pos;
Now complete hooking for imageview from your xib file to ball(declared in .h file).
Now open your .m file and place this code:
-(void)viewDidLoad
{
[super viewDidLoad];
pos = CGPointMake(14.0,7.0);
[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
-(void) onTimer
{
ball.center = CGPointMake(ball.center.x+pos.x,ball.center.y+pos.y);
if(ball.center.x > 320 || ball.center.x < 0)
pos.x = -pos.x;
if(ball.center.y > 460 || ball.center.y < 0)
pos.y = -pos.y;
}
精彩评论