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

本文详细介绍了如何在Chipmunk物理引擎中定义球体的body、形状和属性,包括使用cpBodyNew初始化body,通过cpCircleShapeNew等函数创建形状,以及设置弹性、摩擦等属性。通过实例代码展示了具体操作步骤。

Defining the ball's body and shapes

 

 

 

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

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

// Create our ball's body with 100 mass  
// and infinite moment

cpBody *ballBody = cpBodyNew(100.0, INFINITY);

// Set the initial position

ballBody->p = cpv(160, 250);

// Add the body to the space

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)

 

 

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

 

// Create our shape associated with the ball's body  

cpShape *ballShape = cpCircleShapeNew(ballBody, 20.0, cpvzero);

ballShape->e = 0.5; // Elasticity

ballShape->u = 0.8; // Friction

ballShape->data = ball; // Associate with out ball's UIImageView

ballShape->collision_type = 1; // Collisions are grouped by types

// Add the shape to out space

cpSpaceAddShape(space, ballShape);

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值