Category: Learning Diary

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 #10: Lua, socket server, path finding, quaternions

 

12/Jul/2010

Using Lua and a Socket Server to test and debug iPhone Games

Damn, too many balloons. Ops, just change the Lua code real time!

Damn, too many balloons. Ops, just change the Lua code real time!

I already talked about #iDevBlogADay. But let’s say it again: I just love this “group”! The first thing I do when I wake up is checking the feed for the day’s articles. And how sad I get if an author hadn’t published his take yet.

Everyday we get 2 new nice articles from fellow indie (or established or beginners – like me)  game developers. One of these articles “Tweak Away” from Mystery Coconut brings Lua and socket servers into your iPhone game development.

Main points you’ll learn from the article:

  • How to open a debug server for your game.
  • How to integrate Lua into your game and how it can access your game elements.
  • Change your game behaviors and state via command line (e.g.: no more re-compiling to change the speed of a ball).
  • Scripting all of your game content and behavior.

And yes, Miguel makes everything that easy for us :)

Path Finding

  • Path finding class for a RTS game: ASIPathFinder. “ASIPathFinder is a complete implementation of a cooperative path finding algorithm, and will probably be most useful for writing Real Time Strategy games. It is written in Objective-C, and is compatible with Mac OS and iPhone OS.”
  • Cocos2D, Path finding and Tile maps – sample app: cool working code which I found on Cocos2D forums.

Cocos2D

  • RenderTexture: let’s explain via an example: for a shooter game which leaves bullet holes, we could use sprites for these holes, but a RenderTexture is memory saver.
    a) Sprites: 500 holes – 500 sprites – 1000 triangles – 2000 vertexes.
    b) RenderTexture: will draw only one sprite – it takes a picture and work in that picture.
  • EAGLView: create the OpenGL context.

Drawing with Quartz2D

  1. Save current context
  2. Perform a single combined matrix transformation
  3. Draw graphics to this transformation
  4. Restore context

Source: Beginning iPhone Games Development

Quaternion

  • Sum of a scalar and a vector
  • The quotient of two vectors
  • Imaginary number: i * i = -1
  • A quaterion is a complex number extension: 3 numbers all square roots of -1: i, j, k
  • j * j = -1, k * k  = -1
  • q = w + xi + yj + zk (w = real, x, y, z = complex).
  • or q = [w, v] (w = scalar, v = (x,y,z) – vector)

Source: http://www.gamedev.net/reference/articles/article1095.asp, http://www.paradeofrain.com/2010/07/lessons-learned-in-tilt-controls/

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/

Learning Diary #6: Ideas and Research

 

27, 28, 29/Jun/10

  • A lot of game ideas are being discussed and planned around here. Still we can’t decide one THAT good tho.
  • Days invested researching ideas and grabbing materials. Or at least to get some inspiration.
  • On 29/Jun we finally came up with 3 good and reasonable game ideas, which we decided we are going to develop! – they will be announced soon.

Learning Diary #5: iPhone inspirational stories and Cocos2D concepts

 

26/Jun/10

Developers Stories

  • iPhone Layout

    15 years old spanish teen that made a successful iPhone game and contributes to Cocos2D (wrote CCArray as a substitute to NSArray = performance): Manuel Martínez-Almeida from http://abstractionworks.com/ – I started when I was 8, but with web programming, so very impressive! Congratulations Manuel!

  • The top AppStore sellers have some good inspirational stories: Lima Sky (Doodle Jump – 5 million downloads), Demiforce (Trism – one of the first iPhone game dev and “From Rags to Riches“), Ethan Nicholas (iShoot history).
  • Ethan Nicholas, developer of a tank artillery game called iShoot, told Wired.com he quit his job the day his app rose to No. 1 in the App Store, earning him $37,000 in a single day.

  • All of Pangeasoft‘s (Brian Greenstone) videos are educative, fun and inspirational. Engimo‘s history and video is very interesting. Also don’t forget to check all of his videos.

Cocos2D

Some Cocos2D API:

  • Actions simultaneously: Spawn
  • Actions one after another: Sequence
  • CallFunc: put it as a param to a sequence/spawn
  • Repeat/RepeatForever

General

Learning Diary #4: Switching to Cocos2D and Objective-C

 

24/Jun/10

  • Cocos2D

    After studying deep the licenses behind Unity I decided I’m not going to use it anymore.

  • Since most of the games I have in mind are 2D there is no need to Unity (but this can be controversial to my first entry: programming the game X programming the engine).
  • My choice now is Cocos2D. Why? There are so many published games that use Cocos2D, so it has proven its value. Also, I’ll save a thousand dollars, since cocos is free and open source.
  • The only drawback (or not) is that I’ll have to code stuff that Unity makes painless, but I think I can get along with that pretty fast. Cocos2D has hundreds of resources, and a lot of open source games and code examples. Also, most cocos powered games are very polished, and of all kinds. I just felt in love with Cocos2d!
  • Studied a lot about the iPhone touches and multi touch.

Objective-C

I’ve studied Objective-C on March, so I still have the notes and the mind map I made. It was easy to refresh the mind about it. I like this language – it makes me feel “warm and safe”.

  • NSCoding – serializer.
  • NSKeyedArchiver
  • NSUserDefaults
    [NSUserDefaults standardUserDefaults]
  • Selectors: function pointers. The type is SEL.
  • SEL compare Selector = @selector(compare:options:)
  • SEL name = NSSelectorFromString / NSStringFromSelector
  • To test:
    [object respondsToSelector:selectorVar]
  • To call:
    [object performSelector:selectorVar]

Books:

Learning Diary #3: Game Design

 

23/Jun/10

  • Day dedicated to Game Design, since I still had doubts about Game Design Documents.
  • Read some articles on Gamasutra and a Wiki about Game Maker – tho it had some simple game design explanations.
  • Also read some chapters of the books: Game Architecture and Design, Game Design Foundations and Game Theory and Practice.
  • Made a doc with the main points from everything I’ve read. Very good as a GDC (Game Design Document) template.

Links:

Books:

Learning Diary #2: Site and Unity

 

22/Jun/10

  • Created a simple, but meaningful logo (yet I still don’t like it, will fix it on another time).
  • Registered karnakgames.com and launched this WordPress blog. It has a simple design, but enough to get around until we need a better solution.
  • Studied everything about the Unity3D interface through some tutorials and official documentation.
  • Played around with their official 2D Platform example.

Links: