Tag: box2d

Learning Diary #11: Memory management, iPad and Box2D

 

Wow! It’s been a long time (2 months and 2 days) since I posted and a lot of things happened meanwhile. I can’t exactly cite all the stuff I learned – following the method from earlier diary entries – so I’ll write just some points, since I didn’t keep track of everything learned on these last 62 days. Also, I’m already on the first position of #iDevBlogADay waiting list, so the next posts will be “real” posts.

And how is the game programming going? I’m working on 3 prototypes (less talk, more rock, huh?), which I plan to announce here soon! :)

Learning Diary #11 entries?

Objective-C

  • Programming in Objective-C 2.0I’ve finally understood everything about Objective-C memory management, thanks to the book Programming in Objective-C (2nd ed.). If you want to dive into iOS and/or Mac development I recommend that you read this book first. It explains everything about the core Objective-C in a clean and simple way – ok, sometimes it is too simple (it is a book for non programmers too), but once you get deep into it, it’s all about Objective-C in its roots. It also has the best coverage I’ve seen on Copying and Archiving objects. Check its Table of Contents.
  • [origin release]: if no one else is using the origin, the release will end up invoking the dealloc method on the origin anyway to free up its space.
  • Static Typing: the variable is always used to store objects from the particular class as opposed to id, example (a dull one):
    // id
    id number;
    Fraction *myFraction;
    myFraction = (Fraction *)number;
  • @class identifier: Informs that identifier being used in the is a class. If there is a need to use these class’ methods, use #import instead.
  • Categories: can’t add instance variables, have access to instance variables of the original class, affects all subclasses of the class which is being added a category. Example: if we want to add a method to NSString, just declare a NSString category! NSString (CategoryName).
  • Auto retain and arrays: storing an element in an array creates an automatic increase in the reference count, while assigning it to another variable does not, so we must retain by hand.
  • Notes about nil-ing out pointers: http://wilddogcow.tumblr.com/post/1117200379/nil-ing-out-pointers

iPad

  • Finally got an iPad and learned what the iOs SDK brings exclusively to the iPad. Also at the moment I’m working on a nice client contract work, doing a magazine iPad App :). It’s something exciting and lovely to work with.

Flash and Flex

  • This is something I’d been delaying forever too, so I’m into ActionScript, finally! Thanks to the amazing Cartoon Smart tutorials.

Box2D

  • These notes are from Ray’s tutorial: How To Use Box2D For Just Collision Detection with Cocos2D iPhone: when defining Box2D custom shapes, make sure that your polygon is convex and have at max (default) 8 vertices.
  • Also, when setting up the vertices: “it’s better to use the “Initialization” style and the b2PolygonShape::Set method rather than the “Assignment” style so that Box2D can automatically compute the centroid and the normals for the shape for us” (source).

Art Side

I’ve been studying art and I started drawing, “pixeling” and so on and I have a lot to say about this subject. You can wait some posts around these subjects around here now and not just programming. I have some tips on how to go from a terrible artist to start doing something reasonable and they will be published on the next article.

Learning Diary #9: Cocos2D and Tile maps and more Box2D

 

06/Jul/2010

Tiled (my map is awful, I know)

Tiled (my map is awful, I know)

  • Another day invested reading Ray Wenderlich tutorials! This time, I’ve read his last two tutorials @Box2D and the ones about Cocos2D with tiled maps from Tiled. Pretty easy and clear:
    - How To Create A Breakout Game with Box2D and Cocos2D Tutorial: Part 1 and Part 2.
    - How To Make a Tile Based Game with Cocos2D and Collisions and Collectables: How To Make a Tile Based Game with Cocos2D Part 2.
  • What can I say about these tutorials? Well, I learned almost every concept behind Cocos2D, Box2D, tiled maps and some more concepts (like general game structure, how to put together Physics, general game loop, AI – even if he doesn’t cite AI, and so on). I already had some game development background (I read gamedev books for 6 years already), but even if you are starting, you will get a lot of knowledge reading them.
  • Objective-C: GamingHorror commented on last post that Objective-C can remove an object from an array while iterating through it if using a regular loop (as in C and C++). We just can’t remove an object if using a fast numerator (for..in). Thanks Steffen for the tip!
  • I was reading the source code from C++ STL find iterator and I saw on the documentation:
    // @return The first iterator @c i in the range @p [first,last) such that @c *i == @p val, or @p last if no such iterator exists.

    I was scared for not remembering what [a,b) meant. So, time for some Wikipedia about math and here we have a little refreshment on math sets and intervals notations:

    () exclude
    [] include
    ][ exclude
    Ex: [a,b) = a <= x < b

Cocos2D and Tiled

  • For the sake of curiosity, on 2004 I posted on Gamedev.net (I am the poster Maquiavel) forums a topic with links to sprites' sites: http://www.gamedev.net/community/forums/topic.asp?topic_id=272386. It is still rocking! Although most of the listed sprites are copyrighted, they may be useful to in-house prototyping or just curiosity. I don't know why I made that topic, since I'm only make into game development now, maybe because I love to see those sheets full of colors and life.
  • We get performance if we put all of our animations in one big sprite sheet (max. dimension: 1024x1024). That can be easily accomplished using Zwoptex.
  • Tiled has tile layers and object layers (boxes around portions of the map to specify events).
  • Cocos' convertToNodeSpace: as an example the user clicks in the viewpoint (scrolling camera) at 100,100. But let's say the map is scrolled to 800,800. convertToNodeSpace matches the touch with the scrolling / node zoom / etc.
  • CCTMXTiledMap: it's a CCNode (position, scale, rotation, etc). Its children are layers (CCTMXLayer) of the map generated with Tiled. CCTMXLayer is a CCSpriteSheet, which means we can only have one tileset per layer.
  • Helper function to convert from screen coordinates to tile coordinates:
    // Helper: Position to Tile Coord (upper left, increments each tile)
    // @author http://www.raywenderlich.com
    - (CGPoint)tileCoordForPosition:(CGPoint)position {
        int x = position.x / _tileMap.tileSize.width;
        int y = ((_tileMap.mapSize.height * _tileMap.tileSize.height) - position.y) / _tileMap.tileSize.height;
        return ccp(x, y);
    }

Box2D

  • Box2D

    When giving values to Box2D: pixels/PTM_RATIO

  • When getting values from Box2D: boxvalue * PTM_RATIO (obviously)
  • Mouse joint: makes a body move toward a specific point. Requires:
    - 2 bodies: static or moving body and body you want to move (Box2D manual note: All joints are connected between two different bodies. One body may static. Joints between static and/or kinematic bodies are allowed, but have no effect and use some processing time.).
    - Target: where to move.
    - Collide Connected: when both bodies collide, treat as collision.
    - Max Force: less force, less reaction from our movements.
  • setAwake: for objects that sleep.
  • linearDamping: to reduce speed from a moving body.
  • Contact Listener: it will be called by Box2D when 2 objects begin to touch and stop touching. Btw, we can't store references to the contact points, because Box2D reuses them. We need to copy them inside our contact listener.
  • setAsBox: we have to pass half dimensions.

Learning Diary #8: A*, Cocos2d and Box2d concepts

 

05/Jul/10

A* Search algorithm

Cocos2D

  • Transform anchor: coordinates used by Cocos to rotate objects on screen. For sprites, the default is the middle of the image.
  • ccp(x, y) is Cocos shortcut macro to CGPointMake.
  • Scene: a container of all the stuff you’re going to show on screen in a specific part of your game: Main menu, level, help, highscores (each one is a different scene).
  • Hierarchy: Scene : Layer : Node : Node.

    Cocos2D Scene and Layers

    Cocos2D Scene and Layers

  • A node can be a sprite, label, etc. Note that a sprite may have a child sprite.
  • Add nodes to a layer with addChild method.
  • Scenes have depth ordering (z): lower Z objects appear behind higher Z ones (er, ok, very old thing, we learn this when we are 8? but always worth noting :) ).
  • Cocos auto dealloc all children.
  • Run an action:
    [node (sprite, etc) runAction:[CCSequence (or CCSpawn) actions:action1, action2, CCCallFunN (callback on the object when the actions are performed)]].
  • How to load a sprite:
    CCSprite *sprite = [CCSprite spriteWithFile:@"image.png" rect:CGRectMake(0, 0, w, h)];
    sprite.position = ccp(x, y);

Coordinates

  • UIKit: 0,0 from top left.
  • Cocos2d: 0,0 from bottom left.
  • Sprites: 0,0 from bottom left.

Box2D

  • Box units are in “meters” ranging from 0.1 to 10. Use macro: PTM_RATIO 32.0 to convert pixels to meters, example:
    b2Vec2(winSize.width/PTM_RATIO, 0);
  • World object: manages all the objects and the physics simulation.
  • Bodies: movable and static.

Body

  1. Definition (b2BodyDef): The body definition holds the data needed to create and initialize a body – position, velocity, type.
  2. Object (b2Body): “body factory”: myWorld->CreateBody(&bodyDef);
  3. Shape (b2PolygonShape, b2CircleShape, etc): geometry you wish to simulate.
  4. Fixture definition (b2FixtureDef): binds a shape to a bodys. Shapes don’t know about bodies, that’s why we need fixtures. Defines:
    4.1) Density (more dense, more mass = harder to move).
    4.2) Friction (0…1 – how hard for objects to slide against each other).
    4.3) Restitution (how “bouncy” is an object. 0 = no bounce, 1 = perfectly elastic).
  5. Fixture object (b2Fixture): b2Fixture* myFixture = myBody->CreateFixture(&fixtureDef);. A body may have any number of fixtures.

Cocos2d Image credits: Official wiki

Learning Diary #7: Cocos2D example codes and Box2D engine

 

30/Jun/10

  • I bought an iPod Touch and already got my Apple Developer Certificate.
  • Box2D

  • Started playing around with Cocos2D test codes. It comes packed with a lot of examples, being pretty easy and straightforward to learn. I’m loving it. It makes everything easy.
  • Decided I’ll use Box2D to the physics. It has a complete documentation, as I read it is more mature, and it is C++ (which I prefer instead of straight C). Also, I understood easier its code comparing to Chipmunk.
  • Spent the rest of the day trying to fix the timestep from Box2D examples which come with Cocos2D. I was following the famous Gaffer’s article and managed to put the code and make it worked, but I don’t know where I failed that the code started running at 50-60 fps, and then when I added 15 boxes the fps dropped to 0.5 ~ 1.0! Until now I don’t know how to fix it.
  • At least I got a good Box2D understanding and got some more knowledge about Game performance and when dealing with a lot of objects in the same screen.
  • Also downloaded some examples using Box2D, but none of them have fixed timestep.

Source Code from Box2D example with fixed timestep:

-(void) tick: (ccTime) dt
{
	int32 velocityIterations = 8;
	int32 positionIterations = 1;
	float fixedTimeStep = 1.0/60.0f;
	float timeToRun = dt + timeAccumulated;	

	while(timeToRun >= fixedTimeStep) {
		world->Step(fixedTimeStep, velocityIterations, positionIterations);

		//Iterate over the bodies in the physics world
		for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
		{
			if (b->GetUserData() != NULL) {
				//Synchronize the AtlasSprites position and rotation with the corresponding body
				CCSprite *myActor = (CCSprite*)b->GetUserData();
				myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
				myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
			}
		}

		timeToRun -= fixedTimeStep;
	}

	timeAccumulated = timeToRun;
}

Note that I implemented the accumulator. I think I’m going wrong when stepping Box2D. But I’ll discover that later.

Links:

Resources:

Image credits: Box2D logo, from http://box2d.org/