Categories
Articles

Kobold2D XCode 4 Introduction Tutorial Lesson 2 – Set Landscape Orientation


<== Lesson 1 || Lesson 3 ==>

The first lesson put into place all the accelerometer code for our game. However we want the game to run only in landscape orientation.

Learn cocos2D Game Development
Learn cocos2D Game Development

KKStartupConfig – Setting the device orientation in Kobold2D is done in the config.lua configuration file. We saw in the last lesson the use of FirstSceneClassName for the KKStartupConfig object. FirstSceneClassName is a property for KKStartupConfig. The documentation for KKStartupConfig lists all the properties and valid values.

DeviceOrientation – One of the KKStartupConfig properties is DeviceOrientation. This is an int data type and has four values: DeviceOrientation.Portrait, DeviceOrientation.PortraitUpsideDown, DeviceOrientation.LandscapeLeft, and DeviceOrientation.LandscapeRight.

You can think of them based on where the home button is located. For DeviceOrientation.Portrait the home button is on the bottom where you might expect. For DeviceOrientation.PortraitUpsideDown the home button on top. The home button is to the right for DeviceOrientation.LandscapeLeft to the left for DeviceOrientation.LandscapeRight.

AutoRotationType – Another KKStartupConfig property dealing with rotation is AutoRotationType. This is an int and has these values: Autorotation.None, Autorotation.CCDirector, and Autorotation.UIViewController.

The None setting will never rotate your app’s device orientation. This is the setting we want.

The CCDirector setting makes the CCDirector responsible for rotating the OpenGL view but it will not auto rotate UIKit Views.

The UIViewController setting allows both UIKit views and the OpenGL view to be auto rotated and provides a rotation animation. But it comes with a performance penalty on 1st and 2nd generation iOS Devices. For that reason you can explicitly disable auto rotation on those devices via the AllowAutorotateOnFirstAndSecondGenerationDevices KKStartiupConfig property. We set AllowAutorotateOnFirstAndSecondGenerationDevices to false as we are not supporting older devices.

ShouldAutorotateTo… – Two other rotation KKStartupConfig properties are ShouldAutorotateToLandscapeOrientations and ShouldAutorotateToPortraitOrientations both boolean values. They explicitly restrict auto rotation and are useful when your game does not have alternative views.

Finished Lesson Running on IPad2 Simulator

[ad name=”Google Adsense”]
Lesson Downloads

  1. Game piece images for project
  2. IPhone images for project. Icons and splash screen.
  3. Completed Project. This is built in Kobold2d 1.0.1.

Step 1 – Build an Empty-Project Template

You can continue with the Lesson 1 project and make changes noted here. Otherwise the steps for creating this project from an Empty-Project template are the same as Lesson 1 except to substitute Lesson 2 for Lesson 1 in the project name.

Step 2 – Set the Orientation Properties in config.lua

This is the config.lua file located in the Projectfiles->Resources group.

Lines 43- 47 show the KKStartupConfig properties set for this lesson. Essentially our settings are saying to set the DeviceOrientation to LandscapeRight so the home button appears on the left and prevent any other orientation change.

Also take note to line 18 updated as a developer choice for the first scene game class.

--[[
* Kobold2D™ --- http://www.kobold2d.org
*
* Copyright (c) 2010-2011 Steffen Itterheim. 
* Released under MIT License in Germany (LICENSE-Kobold2D.txt).
--]]


--[[
* Need help with the KKStartupConfig settings?
* ------ http://www.kobold2d.com/x/ygMO ------
--]]


local config =
{
    KKStartupConfig = 
    {
        -- load first scene from a class with this name, or from a Lua script with this name with .lua appended
        FirstSceneClassName = "GameLayer",

        -- set the director type, and the fallback in case the first isn't available
        DirectorType = DirectorType.DisplayLink,
        DirectorTypeFallback = DirectorType.NSTimer,

        MaxFrameRate = 60,
        DisplayFPS = YES,

        EnableUserInteraction = YES,
        EnableMultiTouch = NO,

        -- Render settings
        DefaultTexturePixelFormat = TexturePixelFormat.RGBA8888,
        GLViewColorFormat = GLViewColorFormat.RGB565,
        GLViewDepthFormat = GLViewDepthFormat.DepthNone,
        GLViewMultiSampling = NO,
        GLViewNumberOfSamples = 0,

        Enable2DProjection = NO,
        EnableRetinaDisplaySupport = YES,
        EnableGLViewNodeHitTesting = NO,
        EnableStatusBar = NO,

        -- Orientation & Autorotation
        DeviceOrientation = DeviceOrientation.LandscapeRight,
        AutorotationType = Autorotation.None,
        ShouldAutorotateToLandscapeOrientations = NO,
        ShouldAutorotateToPortraitOrientations = NO,
        AllowAutorotateOnFirstAndSecondGenerationDevices = NO,

        -- Ad setup
        EnableAdBanner = NO,
        PlaceBannerOnBottom = YES,
        LoadOnlyPortraitBanners = NO,
        LoadOnlyLandscapeBanners = NO,
        AdProviders = "iAd, AdMob",	-- comma seperated list -> "iAd, AdMob" means: use iAd if available, otherwise AdMob
        AdMobRefreshRate = 15,
        AdMobFirstAdDelay = 5,
        AdMobPublisherID = "YOUR_ADMOB_PUBLISHER_ID", -- how to get an AdMob Publisher ID: http://developer.admob.com/wiki/PublisherSetup
        AdMobTestMode = YES,

        -- Mac OS specific settings
        AutoScale = NO,
        AcceptsMouseMovedEvents = NO,
        WindowFrame = RectMake(1024-640, 768-480, 640, 480),
        EnableFullScreen = NO,
    },
}

return config

[ad name=”Google Adsense”]
Step 3 – Update the Lesson Subtitle in the GameLayer.m file

Line 45 of the Lesson 2 GameLayer.m file updates the subtitle and included here for completeness. But you can see no other programming changes to control the orientation.

Notice on line 33 and 88 that we did not change but still allows the game to know the dimensions of the screen despite the landscape orientation.

/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim. 
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import "GameLayer.h"

@interface GameLayer (PrivateMethods)
@end

// Velocity deceleration
const float deceleration = 0.4f;
// Accelerometer sensitivity (higher = more sensitive)
const float sensitivity = 6.0f;
// Maximum velocity
const float maxVelocity = 100.0f;

@implementation GameLayer

-(id) init
{
	if ((self = [super init]))
	{
        // Enable accelerometer input events.
		[KKInput sharedInput].accelerometerActive = YES;
		[KKInput sharedInput].acceleration.filteringFactor = 0.2f;
        // Graphic for player
        player = [CCSprite spriteWithFile:@"green_ball.png"];
		[self addChild:player z:0 tag:1];
        // Position player        
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
		float imageHeight = [player texture].contentSize.height;
		player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);
		glClearColor(0.1f, 0.1f, 0.3f, 1.0f);
		// First line of title
		CCLabelTTF* label = [CCLabelTTF labelWithString:@"Kobold2d Intro Tutorial" 
                                               fontName:@"Arial"  
                                               fontSize:30];
		label.position = [CCDirector sharedDirector].screenCenter;
		label.color = ccCYAN;
        [self addChild:label];
        // Second line of title
 		CCLabelTTF* label2 = [CCLabelTTF labelWithString:@"Lesson 2"
                                                fontName:@"Arial"
                                                fontSize:24];
		label2.color = ccCYAN;
        label2.position = CGPointMake([CCDirector sharedDirector].screenCenter.x ,label.position.y - label.boundingBox.size.height);
        [self addChild:label2];
        // Start animation -  the update method is called.
        [self scheduleUpdate];;
	}
	return self;
}
-(void) dealloc
{
#ifndef KK_ARC_ENABLED
	[super dealloc];
#endif // KK_ARC_ENABLED
}

#pragma mark Player Movement
-(void) acceleratePlayerWithX:(double)xAcceleration
{
    // Adjust velocity based on current accelerometer acceleration
    playerVelocity.x = (playerVelocity.x * deceleration) + (xAcceleration * sensitivity);
    // Limit the maximum velocity of the player sprite, in both directions (positive & negative values)
    if (playerVelocity.x > maxVelocity)
    {
        playerVelocity.x = maxVelocity;
    }
    else if (playerVelocity.x < -maxVelocity)
    {
        playerVelocity.x = -maxVelocity;
    }
}
#pragma mark update
-(void) update:(ccTime)delta
{
    // Gain access to the user input devices / states
    KKInput* input = [KKInput sharedInput];
    [self acceleratePlayerWithX:input.acceleration.smoothedX];
    // Accumulate up the playerVelocity to the player's position
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    // The player constrainted to inside the screen
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    // Half the player image size player sprite position is the center of the image
    float imageWidthHalved = [player texture].contentSize.width * 0.5f;
    float leftBorderLimit = imageWidthHalved;
    float rightBorderLimit = screenSize.width - imageWidthHalved;
    // Hit left boundary
    if (pos.x < leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Hit right boundary
    else if (pos.x > rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        // Set velocity to zero
        playerVelocity = CGPointZero;
    }
    // Move the player
    player.position = pos; 
}  
@end

Step 4 – GameLayer.h file

There are no changes from Lesson 1 for the GameLayer.h file. It is included here for completeness.

/*
 * Kobold2D™ --- http://www.kobold2d.org
 *
 * Copyright (c) 2010-2011 Steffen Itterheim. 
 * Released under MIT License in Germany (LICENSE-Kobold2D.txt).
 */

#import "kobold2d.h"

@interface GameLayer : CCLayer
{
    CCSprite* player;
    CGPoint playerVelocity;
}
@end

<== Lesson 1 || Lesson 3 ==>


[ad name=”Google Adsense”]