[译]Chipmunk教程 - 3 初始化

初始化 Chipmunk

 

初始化Chipmunk需要三件事情要去做:

  1. 初始化它
  2. 使用一个 timer 来让Chipmunk计算模拟器的步骤。
  3. 创建并且配置Space

 

初始化Chipmunk是很简单的一部分,你只需要调用cpInitChipmunk 函数就行了,把它放在程序初始化的地方。时间的设置,使用一个简单的NSTimer对象,或者一些你想要使用的游戏引擎。也许你要用的Timer就在引擎自身里面。最后,创建一个新的Space,只需要使用cpSpaceNew方法就行了。

为了完成这三步,只需要再你的controller文件,引入chipmunk.h头文件就好了。

  1. #import "chipmunk.h"  

 

之后,在文件的开始,定义两个可以存储我们space的变量,以及两个方法,当头文件定义完了以后,将会看到如下的效果:

  1. #import <UIKit/UIKith.>  
  2.   
  3. #import "chipmunk.h"  
  4.   
  5. @interface ChipmunkTutorialViewController : UIViewController {  
  6.   
  7. UIImageView *floor; // Holds our floor image  
  8.   
  9. UIImageView *ball; // Holds our ball image  
  10.   
  11. cpSpace *space; // Holds our Space object  
  12.   
  13. }  
  14.   
  15. - (void)setupChipmunk; // Bootstraps chipmunk and the timer  
  16.   
  17. - (void)tick:(NSTimer *)timer; // Fires at each "frame"  
  18.   
  19. @end  

 在实现文件里面,viewDidLoad调用这个方法。:

  1. [self setupChipmunk];  

最后,实现我们声明的两个方法:

  1. // Bootsraps chipmunk and the timer  
  2.   
  3. - (void)setupChipmunk {  
  4.   
  5. // Start chipmunk  
  6.   
  7. cpInitChipmunk();  
  8.   
  9. // Create a space object  
  10.   
  11. space = cpSpaceNew();  
  12.   
  13. // Define a gravity vector  
  14.   
  15. space->gravity = cpv(0, -100);  
  16.   
  17. // Creates a timer firing at a constant interval (desired frame rate)  
  18.   
  19. // Note that if you are using too much CPU the real frame rate will be lower and  
  20.   
  21. // the timer might fire before the last frame was complete.  
  22.   
  23. // There are techniques you can use to avoid this but I won't approach them here.  
  24.   
  25. [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(tick:) userInfo:nil repeats:YES];  
  26.   
  27. }  
  28.   
  29. // Called at each "frame" of the simulation  
  30.   
  31. - (void)tick:(NSTimer *)timer {  
  32.   
  33. // Tell Chipmunk to take another "step" in the simulation  
  34.   
  35. cpSpaceStep(space, 1.0f/60.0f);  
  36.   
  37. }  

 

posted @ 2010-04-01 22:42  AlexLiu  阅读(2100)  评论(0编辑  收藏  举报