Month: July, 2010

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/

Love what you do. Escape the rat race.

 

Inspiration

Why aren’t you being everything you can be right now?

Gabrielle Bouliane, which was diagnosed with Stage Four Cancer and passed away on 01/29/10.

If you aren’t working right now on your best idea or seeking your dreams, then you are doing everything wrong.

REWORK, ©37signals.

#iDevBlogADay

First, if you don’t know #iDevBlogADay yet, you should go to www.idevblogaday.com and see what a wonderful idea. From the site:

“iDevBlogADay is a group of indie developers that want to blog more regularly. Each day of the week is assigned to 2 people. Each person writes in his own blog about whatever he wants. Then they tweet about it with the #iDevBlogADay  hash tag. If a person doesn’t blog during his assigned day, his spot is given to a different developer”.

I am on the waiting list already, but the most important: I’m following each developer on the Twitter. Everyday I read amazing and valuable things from them, as today’s post from We Heart Games: Take the wide turn, love what you do. I am on the same boat as him, to not say that our story is identical.

A little story about myself

I started programming when I was 8, because I wanted to make games.

But everything started “wrong”. I learned Delphi on that time and started doing database applications. When I was 10 I wrote a small “Wap Web Editor” (a text editor with HTML and Wap’s cards syntax highlighting and support buttons) which was published in a Brazilian Web magazine with CD-Rom companion – I was featured due to my age and so on. And my Delphi’s journey ended there.

After that I wanted to write an emulator’s site, so I got SAMS Teach yourself ASP 3 in 21 days. I made my emulators and roms website (which had peaks of 3.000 Brazilian visitors a day) and wrote some websites freelancing (my father has arranged some contacts, since I was too young) until I met PHP.

On this side, I started “right”. I wrote a bunch of tutorials and articles in the biggest Brazil’s PHP and Web development communities. Since then, PHP was my gold mine. From my 15 years old to date I made almost all my cash with PHP. I wrote all kind of websites and webapps, for all company sizes. Then I learned Ruby on Rails – but note something: I was still keeping myself in the web development world.

As a hobby I have always read game development books or stuff that would help me make games: C++ books, algorithms, and so on.

Just for money

I’ll be honest. I actually never felt something special or passionate while working with web development. I have always worked with a feeling of hurry, because I never did what I wanted and what I dreamed. It actually drove me to a lot of frustration periods. And actually, when thinking about doing websites I have a very bad feeling. I’m just tired of doing it. It’s awful to not do what you dream and love.

Then why do I have always worked with it?

  1. My professional career was all based on web development, so I was scared of shifting focus (I think most persons are tied to this rat race).
  2. It always gave me a good money.

But, as I said, if I was frustrated or even hating doing this, why keep doing? That’s what was hitting my mind this year.

Forget the money, do what you love!

“It became clear that the biggest risk in life wasn’t making mistakes but regret: missing out on things. He could never go back and recapture the years spent doing something he disliked” †.

Games have always been my passion and they still are. The musics I hear are based on games soundtracks, all of my creative side comes from games, I think “game based” and so on! That’s my real passion! Games are all around me. Games are what make me feel warm and comfortable. And thinking of making my own games is what I really want.

So, since June I stopped doing websites. And decided I will invest almost (see below why not ALL the time) all my time to games.

If you want to have something done, you will have to make it happen and don’t just wait. Mostly important, don’t invest your time and your life in something that doesn’t add any value on the end or that you dislike.

The 4-hour Workweek book has an interesting story about Josh Steinitz, which had cancer. It tells how he started doing ONLY the things he loves and wants, instead of making them for cash or obligation. Why has he done it? Because none of his plans mattered when he knew about the cancer, so he decided to enjoy his life before it was too late (the quotation above). But he is alive and with no cancer. And better than that: he still doing just passionate things! That’s what every one of us should learn: do what you love everyday.

I am half way on the process. Since I need to pay the bills and keep me and my family warm and fed, I actually do 3 days per week some video editing to two TV shows. The rest of the week is totally dedicated to game development (as you can see in the blog, I am in a heavy learning process!). But that’s temporary, until I can use everyday to game development. At least I’m not a full time frustrated-doing-boring-stuff anymore.

Thanks We Heart Games for the nice article!

† The 4-Hour Workweek, p. 268.

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: