Kobold Kit goes Open Source!

On September 5, 2013, in idevblogaday, Kobold Kit, by Steffen Itterheim

With the release of iOS 7 (ETA: Tuesday, Sept. 10th):

Kobold Kit will be available as open source under the MIT License!

We spent a lot of thoughts on how we like to run an open source project. And also why. I’ll start with an executive summary with more (perhaps too many) details in the text.

The Idea: make the project as open and inviting as possible. Let contributors gain control over and take on responsibility for the project based on their contributions. Provide them with ways to promote their work on their own accord.

The Goal: build the Sprite Kit game engine with the help of many developers.

Kobold Kit is supposed to become the “patron project” under whose roof the most valuable Sprite Kit extensions are combined. Website, forum, wiki, blog and store are extended playgrounds shaped by community members. If you’re part of the project, we want you to proudly present and benefit from it.

In essence: we want to get out of the way as much as possible and enable anyone to find their place in the project. Guidance, not dictating, is our guideline.

Continue reading »

Generate Tilemap Physics Collision Shapes with Cocos2D

On June 1, 2013, in idevblogaday, by Steffen Itterheim

Screen Shot 2013-05-31 at 00.59.01 You have a tilemap and you want physics collisions on it? The solution seems obvious: create a rectangle shape for every blocking tile.

But ouch! This solution is not just hugely wasteful and unnecessarily slows down the physics collision code, it also introduces the well known problem of characters getting stuck even on flat surfaces.

This is in particular a problem for Box2D because its collision mechanic doesn’t work well with flat surfaces subdivided into smaller segments (rectangle shapes in this case).

A workable but still very awkward solution to work around this behavior is to create characters with bevelled edges at the character shape’s bottom at the risk of bopping characters as they walk about the map.

Lupines in the Moore Neighborhood

A good solution to generate physics collisions is to implement the Moore Neighborhood algorithm to generate chain shapes which are more suitable for tilemap collisions. The downside is that adding or removing individual blocking tiles at runtime requires updating the shapes – this is not implemented in this project.

Every flat surface, no matter how many tiles form the surface, will then consist of only one straight collision segment. Here’s a quick demo video of the project discussed in this post that shows the algorithm at work and the resulting “game”:

Continue reading »

Detecting collisions on pixel-perfect boundaries is the holy grail of collision detection in 2D games. As such, it seems like the ideal, if not to say perfect, solution to collision detection in general. Yet, it’s also quite complicated and the straightforward solutions don’t perform very well until you start optimizing the code.

This first post focuses on creating a pixel mask by analyzing the raw image data, as proposed over 3 years ago by Ernesto Corvi. It’s the fastest solution if you want to test if a point collides with a pixel on an image, which also works for rotated and scaled sprites. However it does take some optimizing to speed up detecting collisions between a bounding box of a node and the pixel mask, or two pixel masks.

The alternative solution is to render the two colliding objects onto a CCRenderTexture, as developed by Dani and others on the Cocos2D forum. It is able to detect collisions of arbitrarily rotated and scaled sprites but can be expected to be noticeably slower than a pixel mask. I will discuss this solution in a future iDevBlogADay post.

The results will find their way into Kobold2D, to make the solutions readily available to all developers.

Continue reading »

Cocos2D Sources: Zynga Copyright Added

On May 28, 2011, in Games, by Steffen Itterheim

As @GeekAndDad pointed out on Twitter the majority of the cocos2d source code has been updated with a Zynga Copyright. This is in reference to two commits (1) (2) on github in the develop branch of cocos2d-iphone.

The MIT License header now begins with:

* cocos2d for iPhone: http://www.cocos2d-iphone.org
*
* Copyright (c) 2008-2010 Ricardo Quesada
* Copyright (c) 2011 Zynga Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* […]

Meaning?

This just means that changes made in 2011 to the cocos2d source code are copyright by Zynga. Which is to be expected, now that Ricardo is an employee of Zynga.

It doesn’t change anything regarding the MIT license. And it doesn’t imply a transfer of copyright. In fact, since Ricardo is still listed as copyright owner for the years 2008-2010 it is suggesting that there was no transfer of copyright.

Also note that some of the source code in the cocos2d-iphone project is copyright by other developers or companies, whose copyright has not been changed. This includes classes like CCActionEase, CCActionGrid, CCActionPageTurn3D, CCBlockSupport, CCGrabber, CCMotionStreak, CCTexture2D – just to name a few.

Scheduling multiple update selectors

On March 2, 2011, in cocos2d, Programming, by Steffen Itterheim

I have a seemingly simple requirement for my project: each node should have preUpdate and postUpdate methods in addition to the regular update method. Preprocessing and postprocessing before and after all entities have run their “update” logic is a common requirement in game development. Sometimes called the setup stage before processing all entities in the world, and the finalize stage to complete the current game step and possibly resolve collisions or check any win, lose or achievements conditions.

Of course there are alternative and some may argue “better” implementations, after all an experienced game dev might argue that using pre and post update methods are merely signs of a badly designed game update loop (the jury is out on that one). However beginning game developers definitely understand this concept much better and every game-making tool I know implements pre and post updates, so it has its validity. Plus I find it more convenient than “outsourcing” some logic to a central game loop.

On the other hand it’s also bad practice to rely on one node’s update method to be called before or after all others. Especially once you get to prioritizing update method calls among various groups of nodes it’s just going to get you into trouble. If you set the priority wrong just once you can introduce very subtle issues that’ll be hard to track down. Think of some objects not colliding with the player, or some monsters crashing when you shoot at them with a specific weapon. Scheduled methods should never rely on the order they are called for various entities.

Not so easy …

It turns out the system in Cocos2D only allows one update method per node. That means for each node you can only have one update selector, and via the priority parameter you can only control when its update method is called relative to all other nodes’ update method. In that way you can at least ensure that the player’s update method is always called first, or last, depending on your requirements. But it’s bad programming practice to do so.

I thought, why not just schedule a “regular” selector with CCScheduler? Well, they don’t have a priority, and they are always called after any update method, so you could never schedule a “before update” method this way. And those scheduled selectors aren’t meant to be used for selectors that are called every frame due to the additional processing overhead (eg allocating, updating and releasing the CCTimer object, and comparing & updating time elapsed every frame).

So I had to write a class called ScheduleMultiUpdate which creates proxy instances, registers them with CCScheduler to receive an update message of their own, and then they forward that message to the actual node implementing the special update selector. By using the priority you can define if the selector is called before or after the regular update by using a negative (before) respectively a positive priority (after, must be 1 or greater).

Example Code

Here’s an example usage scheduling the beforeUpdate and afterUpdate selectors to be called before and after the regular update method.

[cc lang=”ObjC” height=”550″]
// in interface (.h)
KKScheduleMultiUpdate* multiUpdate;

// in implementation (.m)
-(void) scheduleUpdateMethods
{
multiUpdate = [[KKScheduleMultiUpdate alloc] initWithNode:self];
[multiUpdate scheduleUpdateSelector:@selector(beforeUpdate:) priority:-1];
[self scheduleUpdateWithPriority:priority];
[multiUpdate scheduleUpdateSelector:@selector(afterUpdate:) priority:1];
}

// this has to be cleanup because CCScheduler retains scheduled targets
// we have to give KKScheduleMultiUpdate a chance to unschedule its selectors or it won’t be deallocated
-(void) cleanup
{
[multiUpdate release];
multiUpdate = nil;
[super cleanup];
}

-(void) beforeUpdate:(ccTime)delta
{
}
-(void) update:(ccTime)delta
{
}
-(void) afterUpdate:(ccTime)delta
{
}
[/cc]

Here’s the actual implementation of KKScheduleMultiUpdate and its proxy class. Notice how the KKScheduleMultiUpdate simply retains a list of proxies and creates new ones, while the proxy class registers itself with CCScheduler to schedule its own update method based on the given priority, and then forwards the message to the baseNode. There’s currently no way to unschedule an update selector, but it should be fairly easy to add if you ever need to unschedule an update method while the game is running (I’d rather just use a bool and skip update).

@interface

[cc lang=”ObjC” height=”500″]
#import “cocos2d.h”

/** Allows you to schedule multiple update methods per node. */
@interface KKScheduleMultiUpdate : NSObject
{
CCNode* baseNode;
CCArray* updateProxies;
}

-(id) initWithNode:(CCNode*)node;
-(void) scheduleUpdateSelector:(SEL)selector priority:(int)priority;

@end

/** Since there can be only one update selector scheduled per instance, this proxy will implement
that update method and forward the message to the desired selector. */
@interface KKScheduleMultiUpdateProxy : NSObject
{
id target;
SEL selector;
TICK_IMP impMethod;
}

-(id) initWithTarget:(id)target selector:(SEL)selector priority:(int)priority;

@end
[/cc]

@implementation

[cc lang=”ObjC” height=”500″]
#import “KKScheduleMultiUpdate.h”

@implementation KKScheduleMultiUpdate

-(id) initWithNode:(CCNode*)node
{
if ((self = [super init]))
{
NSAssert(node != nil, @”%@ %@ – node is nil!”, NSStringFromClass([self class]), NSStringFromSelector(_cmd));
baseNode = [node retain];

updateProxies = [[CCArray alloc] initWithCapacity:1];
}
return self;
}

-(void) dealloc
{
CCLOG(@”%@ %@”, NSStringFromSelector(_cmd), self);

[baseNode release];
baseNode = nil;

// must do a cleanup to unschedule CCSelector, this is because CCScheduler retains scheduled targets
[updateProxies makeObjectsPerformSelector:@selector(cleanup)];
[updateProxies release];
updateProxies = nil;

NSAssert([self retainCount] == 1, @”%@ %@ – retainCount on cleanup should be 1 but is %i”, NSStringFromClass([self class]), NSStringFromSelector(_cmd), [self retainCount]);

[super dealloc];
}

-(void) scheduleUpdateSelector:(SEL)selector priority:(int)priority
{
NSAssert([baseNode respondsToSelector:selector], @”%@ %@ – node %@ does not respond to selector”, NSStringFromClass([self class]), NSStringFromSelector(_cmd), baseNode);
// TODO: might want to check here if the selector happens to be already scheduled

KKScheduleMultiUpdateProxy* proxy = [[KKScheduleMultiUpdateProxy alloc] initWithTarget:baseNode selector:selector priority:priority];
[updateProxies addObject:proxy];
[proxy release];
}

@end

@implementation KKScheduleMultiUpdateProxy

-(id) initWithTarget:(id)target_ selector:(SEL)selector_ priority:(int)priority
{
if ((self = [super init]))
{
NSAssert(target_ != nil, @”target is nil”);
NSAssert(selector_ != nil, @”selector is nil”);

target = target_; // weak ref
selector = selector_; // weak ref

impMethod = (TICK_IMP)[target methodForSelector:selector];
NSAssert(impMethod != nil, @”selector is not an instance method of target %@”, target);

[[CCScheduler sharedScheduler] scheduleUpdateForTarget:self priority:priority paused:NO];
}
return self;
}

-(void) cleanup
{
CCLOG(@”%@ %@”, NSStringFromSelector(_cmd), self);

[[CCScheduler sharedScheduler] unscheduleUpdateForTarget:self];
impMethod = nil;

NSAssert([self retainCount] == 1, @”%@ %@ – retainCount after cleanup should be 1 but is %i”, NSStringFromClass([self class]), NSStringFromSelector(_cmd), [self retainCount]);
}

-(void) dealloc
{
CCLOG(@”%@ %@”, NSStringFromSelector(_cmd), self);

[super dealloc];
}

-(void) update:(ccTime)delta
{
impMethod(target, selector, delta);
}

@end
[/cc]

As always, you’re free to use this code. I release it under the MIT License. You do not need to include a copyright notice, but I’d appreciate any mention or backlink to this website.

I almost forgot about the Cocos2D-Project on github. While it works flawlessly with the latest v0.99.5 stable release of Cocos2D, it was still bundled with only the RC1 (release candidate). So I’ve updated the cocos2d version in the repository.

In case you don’t know what Cocos2D-Project is:

Cocos2D-Project is a great way to start any Cocos2D-iPhone based project.

It eases up- and downgrading the Cocos2D game engine at any time. It includes additional source code as well as multiple targets and build configurations for Ad Hoc & App Store distribution (creates the necessary IPA/ZIP files) and debugging of memory leaks and related issues.

Cocos2D-Project is free, open-source, uses the MIT License and comes already bundled with the cocos2d-iphone version that it currently works with “out of the box”.

It’s not affiliated with or endorsed by cocos2d-iphone.org and Ricardo Quesada. You will get support for Cocos2D-Project on Cocos2D Central.

Future updates

With the help of others, the Cocos2D-Project development has taken on a life of its own. The current work in progress is much more than a simple Xcode project referencing just the Cocos2D game engine. I’m looking forward to announce a big update in a couple weeks. Stay tuned.

Tagged with: