Adding sprite texture to physics objects

Until now, we have only added physics bodies, but we haven't added any texture to them. Let's take a look at how to do it.

Getting started

Import the gift.png and ornament.png resources to the file.

How to do it…

It looks as though it is going to be raining gifts, so we will add a new function called spawnGift and the following code:

- (void)spawnGift:(CGPoint) position{

  CCSprite *giftSprite = [CCSprite spriteWithImageNamed:@"gift.png"];

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

  giftBody.type = CCPhysicsBodyTypeDynamic;

  giftSprite.physicsBody = giftBody;
  giftSprite.position = position;


  [_physicsWorld addChild:giftSprite];


}

Here, instead of creating an empty CCNode object, we will create CCSprite and add the physics body to it.

Note that as the gifts are rectangular, we will create a rectangular physics body instead of a circular one. We will pass in the content size of the sprite to the rectangle to make it the same size as the sprite.

In the function, we will pass in the position where we want the object to be created. We will assign this position to the giftSprite object.

And this is all!

In the init function, we will comment the spawnEmptyObject function and add the following instead:

[self spawnGift:CGPointMake(winSize.width/4, winSize.height * 0.9)];

Additionally, we will also create a spawnOrnament function, as follows:

- (void)spawnOrnament: (CGPoint) position{

  CCSprite *ornamentSprite = [CCSprite spriteWithImageNamed:@"ornament.png"];

  float radius = ornamentSprite.contentSizeInPoints.width * 0.5f;

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

  ornamentBody.type = CCPhysicsBodyTypeDynamic;

  ornamentBody.collisionType = @"ornament";

  ornamentSprite.physicsBody = ornamentBody;
  ornamentSprite.position = position;

  [_physicsWorld addChild:ornamentSprite];

}

We name collisionType so that we can sort by which objects are colliding when we check for collisions later.

This is a circle physics object. So the radius of the circle and center point needs to be specified. The physics body is placed at the center of the ornament image.

Add the function in the init function to create it.

  [self spawnOrnament:CGPointMake(winSize.width * 3/4, winSize.height * 0.9)];

Run it to see the code in action.

How it works…

Well, honestly, we are not doing any work here at all. We specified the image and the kind of physics object to create and just called the function, and the physics engine takes care of the rest.

Objects get created at either side of the screen, start at the top, and keep falling down.

How it works…
..................Content has been hidden....................

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