[译]Chipmunk教程 - 5 跟踪球体的运动

Tracking the Ball's movements 跟踪球体的运动

 

目前还没有代码连接到Chipmunk的模拟器上,上图片正常的运行。只有当扩展相应的方法之后,通过Chipmunk同步更新图像的位置才可以。这个过程可以通过多种途径来实现,例如,存储一个需要检查的点的集合。但是很幸运的是,Chipmunk设计了一个非常简单而抽象的过程让其轻松实现。接下来的这段代码就是我们需要写一次并且很少需要更新的,除非其中有一个或者某一个细节从这里移除了。

所以,在创建一个形体shape的最后一步,将会连接到一个特殊的body上,所以我们同样要在同一个shape里面存储一个UIImageView的引用。这意味着,所有的需要的数据都在中间位置,记住,Chipmunk总是提供给我们一个方便的函数:

  1. cpSpaceHashEach(cpSpaceHash * hash, cpSpaceHashIterator func, void * data)  

This function takes a hash (an array), a function to be called for each element in the array and optionally a custom data parameter.

这个函数需要一个哈希数组作为参数,每一个数组里面的参数都会

So, go to the tick method and add this code after the cpSpaceStep call already there:

  1. // Call our function for each shape  
  2.   
  3. cpSpaceHashEach(space->activeShapes, &updateShape, nil);  

 

像我们之前介绍的一样,activeShape数组需要调用updateShape函数,这个将会在下一步实现。当我们实现地板的时候,我们将要讨论这个active的形状,所以不要着急关于这个的细节。

目前我们需要去实现updateShape函数,在开始的地方定义,最好放在其他的函数声明之后:

  1. void updateShape(void *ptr, void* unused); // Updates a shape's visual representation (i.e. sprite)  
  2.   
  3. And then, this code on the implementation file:  
  4.   
  5. // Updates a shape's visual representation (i.e. sprite)  
  6.   
  7. void updateShape(void *ptr, void* unused) {  
  8.   
  9. // Get our shape  
  10.   
  11. cpShape *shape = (cpShape*)ptr;  
  12.   
  13. // Make sure everything is as expected or tip & exit  
  14.   
  15. if(shape == nil || shape->body == nil || shape->data == nil) {  
  16.   
  17. NSLog(@"Unexpected shape please debug here...");  
  18.   
  19. return;  
  20.   
  21. }  
  22.   
  23. // Lastly checks if the object is an UIView of any kind  
  24.   
  25. // and update its position accordingly  
  26.   
  27. if([shape->data isKindOfClass:[UIView class]]) {  
  28.   
  29. [(UIView *)shape->data setCenter:CGPointMake(shape->body->p.x, 480-shape->body->p.y)];  
  30.   
  31. }  
  32.   
  33. else  
  34.   
  35. NSLog(@"The shape data wasn't updateable using this code.");  
  36.   
  37. }  

 

虽然最后一段代码之后1,2行是需要的,但是仍然实现了很多事情。我加入很多检验和警告,这样来让你知道会出现什么问题,但是重要的是需要更新视图的位置。需要注意的是,我们并没有直接的分配Y轴是什么值,这是因为Chipmunk的坐标系统和Cocoa是不一样的。Cocoa系统初始的是左上角是00,Chipmunk是左下角。因为不同的框架有不同的坐标系系统,这样的话在我们实现的时候需要更加注意这些。Cocos2D和Chipmunk的坐标系是一样的。

ball's passing over the floor

 

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