Changing body properties

Each body or shape has certain body properties, such as mass, friction, bounciness, and so on, just like any physical body in nature. Let's take a look at how we can modify these values.

Getting started

There is no additional work to be done here.

How to do it…

For regular bodies that don't have a specific shape attached to them, we will add mass, friction, and bounciness by changing the values of the mass, friction, and elasticity properties of the object.

For the gift body, after creating it, we will add the following lines of code:

  CCPhysicsBody *giftBody  = [CCPhysicsBody
    bodyWithRect:(CGRect){CGPointZero,
    giftSprite.contentSize} cornerRadius:0];

  giftBody.mass = 1.0f;
  giftBody.friction = 0.2f;
  giftBody.elasticity = 0.0f;

If the mass is high, then although the elasticity is defined, the body will bounce less due to the weight.

The friction will stop the movement of the object. The more friction you add, the faster the object will stop. If the friction is set to 0, then when the force is applied, the body will never stop and keep going forever.

Elasticity is just another way of saying how bouncy the object is. Here, we set it to 0 as boxes generally aren't bouncy by nature. However, balls usually are. So, let's add bounciness to our ornament, as follows:

    CCPhysicsBody *ornamentBody = [CCPhysicsBody
      bodyWithCircleOfRadius:radius
      andCenter:ornamentSprite.anchorPointInPoints];

    ornamentBody.mass = 1.0f;
    ornamentBody.friction = 0.2;
    ornamentBody.elasticity = 1.0;

How it works…

Now, run the application, and enjoy the bouncing ornament. Change the value of the bounce to increase or decrease the values.

There's more…

In cases where we specify the shapes, such as in the case of the basket, we need to assign these values to each shape individually. So, in the case of the basket, we assigned the following values:

    CCPhysicsShape *bottom = [CCPhysicsShape rectShape:CGRectMake(14,0,basketSprite.contentSize.width - 28,10)
    cornerRadius:0];

 
    leftWall.mass = rightWall.mass = bottom.mass = 1.0f;
    leftWall.friction = rightWall.friction = bottom.friction = 0.2;

    NSArray* shapeArray = [[NSArray alloc]initWithObjects:leftWall,rightWall,bottom, nil] ;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.254.118