How To Make a Catapult Shooting Game with Cocos2D and Box2D Part 1

This is a blog post by iOS Tutorial Team member Gustavo Ambrozio, a software engineer with over 20 years experience, including over three years of iOS experience. He is the founder of CodeCrop Software. You can also find him on Google+. In this tutorial series we’ll build a cool catapult type game from scratch using […] By Gustavo Ambrozio.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Gratuitous Camera Movement

One thing that would be nice is if we could make the scene move to follow the bullet so we can see it’s whole movement.

We can do this easily by changing the position property of the scene. Add this code to the end of the tick method:

// Bullet is moving.
if (bulletBody && bulletJoint == nil)
{
    b2Vec2 position = bulletBody->GetPosition();
    CGPoint myPosition = self.position;
    CGSize screenSize = [CCDirector sharedDirector].winSize;
    
    // Move the camera.
    if (position.x > screenSize.width / 2.0f / PTM_RATIO)
    {
        myPosition.x = -MIN(screenSize.width * 2.0f - screenSize.width, position.x * PTM_RATIO - screenSize.width / 2.0f);
        self.position = myPosition;
    }
}

The condition checks is there’s a bullet that was attached but is not anymore, so it must be moving. We then get it’s position and check if it’s after the right of the screen’s middle. If it is we change the position of the screen to make the bullet be in the middle of the screen.

Notice the minus sign in front of the MIN. We do this because the position has to be negative to make the scene move to the left.

Try it out. It’s pretty cool now!

Flying acorn with screen scrolling

Where To Go From Here?

The repository tag for this point in the tutorial is BulletCreation.

At this point, you should have a great start of a catapult game – the catapult works quite well! Head over to the next part of the tutorial, where we expand this into a full game with enemies and collision detection!

In the meantime, if you have any questions or comments, join the forum discussion below!


This is a blog post by iOS Tutorial Team member Gustavo Ambrozio, a software engineer with over 20 years experience, including over three years of iOS experience. He is the founder of CodeCrop Software. You can also find him on .

Gustavo Ambrozio

Contributors

Gustavo Ambrozio

Author

Over 300 content creators. Join our team.