Dieses Dokuwiki verwendet ein von Anymorphic Webdesign erstelltes Thema.

Generic Tips and Tricks

DEPRECATED

DEPRECATED

Use this page instead: Tips & Tricks

DEPRECATED

DEPRECATED

Actions

Continuous (never ending) Repeat actions
id _action = [RepeatForever actionWithAction: [MoveBy actionWithDuration:1.0 position:cpv(10,0)] ]

Textures

Problem with texture alpha

Problem with texture alpha ? Set the pixel format of your director like this:

[[Director sharedDirector] setPixelFormat:kRGBA8];

Add depthBuffer to your director like this:

[[Director sharedDirector] setDepthBufferFormat:kDepthBuffer16];
Frame Rate Impact Due to Composite, Transparent Images

Touch Events

Layer isTouchEnabled

Layer isTouchEnabled must be set before adding the layer. Otherwise, it wont receive the touch events.

Touch Events For Anyone

Any NSObject type can receive touch events if your object implements the TargetedTouchDelegate protocol.

// only valid since v0.8
 
@class MyNode <TargetTouchDelegate> : CCSprite
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event;
 
// optional:
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event;
- (void)ccTouchCancelled:(UITouch *)touch withEvent:(UIEvent *)event;
 
@end

CocosNode

Flip or mirror a sprite/image

Scaling by -1 causes a sprite/image to be mirrored/flipped. You can apply the transformation to the x axis, the y axis or both depending on what effect you want.

self.scaleX = -1;
self.scaleY = -1;

Since v0.9, you can also use the flipX and flipY properties. Example:

// only valid since v0.9
sprite.flipX = YES;
sprite.flipY = NO;
Get actual position of sprite taking into account scale, rotation and anchor

How to get the actual position of a sprite taking into account scale, rotation and anchor.

CGPoint absolutePosition = [sprite convertToWorldSpace:CGPointZero];

Code Snippets

Scrolling backgrounds and parallax

Tile Maps

TileMapAtlas gaps between tiles

When using TileMapAtlas the tiles will always have Anti-Aliasing active, so if you don't remove the AA before using the Atlas you'll see lines between each tile. In order to avoid this you have to remove the Anti-Aliasing from that texture.

Code for cocos2d < 0.8.0

// Aliased images
	[Texture2D saveTexParameters];
	[Texture2D setAliasTexParameters];
	TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];
	[Texture2D restoreTexParameters];

Code for cocos2d >= 0.8.0

        TileMapAtlas *tilemap = [TileMapAtlas tileMapAtlasWithTileFile:@"tiles.png" mapFile:@"levelmap.tga" tileWidth:16 tileHeight:16];
	// Aliased images
        [tilemap.textureAtlas.texture setAliasTexParameters];
TMX Tile Map Gaps/Artifacts (Cocos2d v0.8.2)

When using TMX Tile Maps, you may notice strange behaviors such as gaps or artifacts on the map. To resolve it, try the following:

  • Set 2D Projection in the Director
  • Set Alias Parameter for the Tile map (instead of Anti-Alias)
  • If you're updating the camera center/eye, try round your input to an integer instead of passing in a float
  • Disabling Render Subpixel may work as well
Hex tiles

Quick hack to add Hex tiles (0.6.3 / 0.7)

  • Edit updateAtlasValueAt (0.7) or updateAltasValues (0.6.3) in TileMapAtlas.m to include the following
float offsetX = x *( itemWidth *0.5f + ((int)(itemWidth / 4.0f)));
float offsetY =  y * itemHeight;
 
if (x % 2)
{
    offsetY = y * itemHeight + 0.5f * itemHeight;
}
 
vertex.bl_x = offsetX;                    // A - x
vertex.bl_y = offsetY;                    // A - y
vertex.bl_z = 0.0f;                        // A - z
vertex.br_x = itemWidth + offsetX;        // B - x
vertex.br_y = offsetY;                    // B - y
vertex.br_z = 0.0f;                        // B - z
vertex.tl_x = offsetX;                    // C - x
vertex.tl_y = itemHeight + offsetY;        // C - y
vertex.tl_z = 0.0f;                                 // C - z
vertex.tr_x = itemWidth + offsetX;        // D - x
vertex.tr_y = itemHeight + offsetY;        // D - y
vertex.tr_z = 0.0f;                                // D - z

Director

Flicker at startup

How to prevent the flicker/blink when the game is loaded, as discussed here: http://groups.google.com/group/cocos2d-iphone-discuss/browse_thread/thread/6685badf484b29dd

If are using a Default.png image and want use that same image in your initial screen you will notice a flicker / blink.

To get rid of that issue, you could to use this just before running your main scene.

Code for cocos2d < 0.8.0

// prevent flicker
Sprite *sprite = [[Sprite spriteWithFile:@"Default.png"] retain];
sprite.transformAnchor = cpvzero;
[sprite draw];	
[[[Director sharedDirector] openGLView] swapBuffers];
[sprite release];
 
// Run the intro Scene
[[Director sharedDirector] runWithScene: introScene];

Code for cocos2d >= 0.8.0

// prevent flicker
Sprite *sprite = [[Sprite spriteWithFile:@"Default.png"] retain];
sprite.anchorPoint = CGPointZero;
[sprite draw];	
[[[Director sharedDirector] openGLView] swapBuffers];
[sprite release];
 
// Run the intro Scene
[[Director sharedDirector] runWithScene: introScene];

Drawing Primitives

Overview (When to draw)

You should be drawing primitives in a draw method; This means sub-classing a CocosNode type and overloading -(void) draw. Looking at mainLoop in Director, scheduled methods get called, then landscape is applied then drawing is done. If you do drawing in a scheduled method then you are doing it before the landscape transformation is applied.

Social and Ad Networking

Facebook Tutorial
Using AdMob

The following provides the code and steps used to include AdMob ads within your Cocos2D application. Register with AdMob to get a publisher ID. You'll need to input information regarding your application as well. Download their SDK and include the respective files within your project. This will include the adMobView.h and AdMobDelegateProtocol.h files as well as two library files.

Add the following statements to the class header file that will display the ads:

#import "AdMobView.h"
#import "AdMobDelegateProtocol.h"
#define AD_REFRESH_PERIOD 60.0 // display fresh ads once per minute

Declare the following variables:

AdMobView *adMobAd;  
NSTimer *refreshTimer; // timer to get fresh ads

Then include within the class main file that will display the ad the following methods:

- (void)didReceiveAd:(AdMobView *)adView {

	// put the ad at the top middle of the screen in landscape mode
	adMobAd.frame = CGRectMake(0, 432, 320, 48);
	CGAffineTransform makeLandscape = CGAffineTransformMakeRotation(M_PI * 0.5f);
	makeLandscape = CGAffineTransformTranslate(makeLandscape, -216, -134);//centers the ad in landscape mode
	adMobAd.transform = makeLandscape;
	[[[Director sharedDirector] openGLView] addSubview:adMobAd];
	[refreshTimer invalidate];
	refreshTimer = [NSTimer scheduledTimerWithTimeInterval:AD_REFRESH_PERIOD target:self selector:@selector(refreshAd:) userInfo:nil repeats:YES];
}

- (void)onEnter {
	adMobAd = [AdMobView requestAdWithDelegate:self];
	[adMobAd retain];
	[super onEnter];
}

- (void)onExit {
	[adMobAd removeFromSuperview];
	[adMobAd release];
	[super onExit];
}

// Request a new ad. If a new ad is successfully loaded, it will be animated into location.
- (void)refreshAd:(NSTimer *)timer {
	[adMobAd requestFreshAd];
}

// AdMobDelegate methods

- (NSString *)publisherId {
	return @"a1234567890"; // this is your publisher ID
}

- (UIColor *)adBackgroundColor {
	return [UIColor colorWithRed:0 green:0.749 blue:1 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)primaryTextColor {
	return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (UIColor *)secondaryTextColor {
	return [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; // this should be prefilled; if not, provide a UIColor
}

- (BOOL)mayAskForLocation {
	return NO; // this should be prefilled; if not, see AdMobProtocolDelegate.h for instructions
}

This should now display a rotated ad at the top middle of your view in landscape mode.

Third Party

Chipmunk SpaceManager

Chipmunk Spacemanager : Objective-C encapsulation of chipmunk, cocos2d support

Other

Adding Pictures to Forum Posts
tips/generic.txt · Last modified: 2010/03/15 19:09 by admin
Trace: generic
Dieses Dokuwiki verwendet ein von Anymorphic Webdesign erstelltes Thema.
CC Attribution-Noncommercial-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0