如何在iPhone中随机丢球

时间:2010-12-26 21:02:39

标签: iphone cocoa-touch uiimageview

如果有完整的赞美,我可以先宣布我是iPhone编程的新手。因此,我想请求有关如何实现动画的解决方案的帮助,其中“a”球从iPhone屏幕的顶部随机掉落。球的属性使得它具有不同的大小,速度并且可以反弹,即也涉及碰撞。

我正在尝试仅使用球的图像,我通过Interface Builder(IB)添加了球图像,并将UIImageView连接到IB中的文件所有者,我一直试图通过添加以下方式以编程方式访问图像.O文件的IBOutlet关键字(请参阅下面的.h和.m代码)。  当我运行代码时,我得到的是图像出现并立即消失。如何让这个球随着一些弹跳或碰撞随机掉落。

准确地说,我希望有一种动画,例如在iPhone游戏中获得的动画落球......球落在哪里然后仍会反弹。

提前感谢您的帮助 CHEERS !!

***The .h file***

@interface TestBallsViewController : UIViewController {

  IBOutlet UIImageView *ball;

 CGPoint ballMovement;

 double size;
 double speed;

}


@property(nonatomic, retain)IBOutlet UIImageView *ball;


- (void)initializeTimer;


- (void)animateBall:(NSTimer *)theTimer;



**The .m file**

@implementation TestBallsViewController

@synthesize ball;


- (void)dealloc {

 [ball release];

    [super dealloc];
}



- (void)viewDidLoad {
 [super viewDidLoad];
 ballMovement = CGPointMake(2,2);  
 [self initializeTimer];

}



- (void)initializeTimer
 { 
  float theInterval = 0.3;

  [NSTimer scheduledTimerWithTimeInterval:theInterval target:self

                   selector:@selector(animateBall:) userInfo:nil repeats:YES];
}



- (void)animateBall:(NSTimer *)theTimer

 {
  ball.center = CGPointMake(ball.center.x+ballMovement.x, 
                                                       ball.center.y+ballMovement.y);


     int startX =arc4random()%100;
                   int endX = arc4random()%320; 
     ball.frame= CGRectMake(startX, -100, 15.0 * size, 15 * size);
                   ball.frame = CGRectMake(endX, 480, 15.0 * size, 15.0 * size);



  if(ball.center.x > 300 || ball.center.x < 20) ballMovement.x = 
                                                                     - ballMovement.x;
  if(ball.center.y > 440 || ball.center.y < 40) ballMovement.y =
                                                                     - ballMovement.y;

 }

1 个答案:

答案 0 :(得分:0)

- (void)animateBall:(NSTimer *)theTimer

 {
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:1.0];
  ball.center = CGPointMake(ball.center.x+ballMovement.x, 
                                                       ball.center.y+ballMovement.y);


     int startX =arc4random()%100;
                   int endX = arc4random()%320; 
     ball.frame= CGRectMake(startX, -100, 15.0 * size, 15 * size);
                   ball.frame = CGRectMake(endX, 480, 15.0 * size, 15.0 * size);



  if(ball.center.x > 300 || ball.center.x < 20) ballMovement.x = 
                                                                     - ballMovement.x;
  if(ball.center.y > 440 || ball.center.y < 40) ballMovement.y =
                                                                     - ballMovement.y;
  [UIView commitAnimations];

 }