[译]Chipmunk教程 - 4定义球体body和shapes

Defining the ball's body and shapes

 

 

 

定义一个body,同样是一个简单的过程,虽然他需要一些物理方面的知识。Chipmunk 有一个非常方便的函数,cpBodyNew(mass, moment); 它包含了所有的初始化条件和body所包含的东西。通常情况下,剩下的我们需要的就是设置body的位置了。

所以,接下来的代码会定义一个球体的body,这是他的位置,并且把他添加到我们的space当中,把接下来的code放在setupChipmuck 方法的末尾:

  1. // Create our ball's body with 100 mass  
  2. // and infinite moment  
  3.   
  4. cpBody *ballBody = cpBodyNew(100.0, INFINITY);  
  5.   
  6. // Set the initial position  
  7.   
  8. ballBody->p = cpv(160, 250);  
  9.   
  10. // Add the body to the space  
  11.   
  12. cpSpaceAddBody(space, ballBody);  

Next, we need to tell how the ball interacts with other objects by defining its shape and associated properties. This process is usually the most complex of all and sometimes requires some tuning along trial & error. Chipmunk provides you with 3 different functions to create shapes based on the type you desire:

接下来,我们需要告诉这个球体如何和其他的物体进行交互。我们要定义他的形状shape和相关的属性。这个过程通常来说,是一个非常复杂的,并且需要反复的试验。Chipmunk提供了三种不同的函数,根据不同的你需要的类型,创建形状。

  • cpCircleShapeNew(cpBody * body, cpFloat radius, cpVect offset)
  • cpSegmentShapeNew(cpBody * body, cpVect a, cpVect b, cpFloat radius)
  • cpPolyShapeNew(cpBody * body, int numVerts, cpVect * verts, cpVect offset)

这些函数中,变量的意思是:

  • body: the body associated with the shape you're creating
  • radius: the radius of the circle you're creating or the "width" of the line/segment
  • offset: where to place the shape relative to the body's center
  • a, b: the start/end points for segment shapes (it creates a line linking the two points)
  • numVerts, verts: for poly shapes you provide an array of the vertexes defining the shape (due to C constraints you need to pass numVerts which is the number of items/points on that array)

 

所以,现在我们已经有了一个关于如何创建形状,有了一个简单的概览了。剩下的我们需要做得是定义属性了,如果阅读下面的代码注释,也不需要太多的解释了:

  1. // Create our shape associated with the ball's body  
  2.   
  3. cpShape *ballShape = cpCircleShapeNew(ballBody, 20.0, cpvzero);  
  4.   
  5. ballShape->e = 0.5; // Elasticity  
  6.   
  7. ballShape->u = 0.8; // Friction  
  8.   
  9. ballShape->data = ball; // Associate with out ball's UIImageView  
  10.   
  11. ballShape->collision_type = 1; // Collisions are grouped by types  
  12.   
  13. // Add the shape to out space  
  14.   
  15. cpSpaceAddShape(space, ballShape);  

 

你可以定义很多属性,查阅文档的话,你可以了解更多。现在,我们需要做的就是确定设置了数据和碰撞类型。你可能会放弃elasticty和friction,甚至于改变他们的值。

 

 

 

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