Fork me on GitHub

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

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

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

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

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:

// Call our function for each shape  

cpSpaceHashEach(space->activeShapes, &updateShape, nil);

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

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

void updateShape(void *ptr, void* unused); // Updates a shape's visual representation (i.e. sprite)  

And then, this code on the implementation file:

// Updates a shape's visual representation (i.e. sprite)

void updateShape(void *ptr, void* unused) {

// Get our shape

cpShape *shape = (cpShape*)ptr;

// Make sure everything is as expected or tip & exit

if(shape == nil || shape->body == nil || shape->data == nil) {

NSLog(@"Unexpected shape please debug here...");

return;

}

// Lastly checks if the object is an UIView of any kind

// and update its position accordingly

if([shape->data isKindOfClass:[UIView class]]) {

[(UIView *)shape->data setCenter:CGPointMake(shape->body->p.x, 480-shape->body->p.y)];

}

else

NSLog(@"The shape data wasn't updateable using this code.");

}

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

 

 

既然我们最终是需要这个球体进行运动,现在是时候编译并且运行了。如果你是按着这个流程做的,那目前运行的结果应该是,球体从上面掉落下来,然后加速运动,不需要太多时间之后,球体从右侧地盘穿过,这是我们下一步所要做的。





posted on 2012-03-09 23:33  pengyingh  阅读(360)  评论(0)    收藏  举报

导航