Cocos2d game orientation switching left->right->left directly after launch - cocos2d-iphone

I'm using the default cocos2d template with slight modification to the base code.
My game is played on left or right only- no portrait.
When the game launches, it starts right, then flips upside-down, then flips right again.
I looked through several posts on the issue and cannot seem to put my finger on what's making the interface flip back and forth without the device being moved. Appreciate any help!
I have the following related code:
RootViewController.m:
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGRect rect = CGRectZero;
if(toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
rect = screenRect;
else if(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
rect.size = CGSizeMake( screenRect.size.height, screenRect.size.width );
CCDirector *director = [CCDirector sharedDirector];
EAGLView *glView = [director openGLView];
float contentScaleFactor = [director contentScaleFactor];
if( contentScaleFactor != 1 ) {
rect.size.width *= contentScaleFactor;
rect.size.height *= contentScaleFactor;
}
glView.frame = rect;
}
#endif
AppDelegate:
#if GAME_AUTOROTATION == kGameAutorotationUIViewController
[director setDeviceOrientation:kCCDeviceOrientationPortrait];
#else
[director setDeviceOrientation:kCCDeviceOrientationLandscapeRight];
#endif
GameConfig.h:
#define kGameAutorotationNone 0
#define kGameAutorotationCCDirector 1
#define kGameAutorotationUIViewController 2
#if defined(__ARM_NEON__) || TARGET_IPHONE_SIMULATOR
#define GAME_AUTOROTATION kGameAutorotationUIViewController
#elif __arm__
#define GAME_AUTOROTATION kGameAutorotationNone

I had the same problem today, it appeared to be down to the order of supported orientations in my application plist. The app would launch in Landscape Left, flip to right, then flip to left again really quickly.
I went into my project properties in the "Summary" tab (where you configure supported orientations, the app icons, launch images, etc) and deselected all the supported orientations.
I then ticked them again in order (Landscape Right, Landscape Left) - and verified in the "Info" tab that they were in this order in the array, under the "Supported Interface Orientations" section.
Item 0 - Landscape (right home button)
Item 1 - Landscape (left home button)
Not had the problem since, hope this helps.

Related

cocos2dx 3.3 animation implementation

I am new in cocos2dx development.I almost learn all basic level of cocos2dx (version 3.3) in android using cpp language. I showing that there are lots of update over cocos2dx.org.
In android I am currently developing the tetris game using cocos2dx version 3.3, I want to know what is the best way to achieve awesome animation such like ticking bombs, bomb explosion, spinning game score display, popping up and disappearing balloons with game score increments. I was wondering about animation implementation cocos2dx in android using c++. We also need to make game that support the multiscreen support, I had search lots all these points could not able to find much information over the google.
I show sonar system support nicely for beginner level, we really appreciate it , I had watched all videos shared by sonar system over the YouTube. I learn lot over there. I want to know the advance level animation in android in cocos2dx.
We looking any help will appreciate.
Thank you
here is my appmacros.h filr ..
#ifndef __APPMACROS_H__
#define __APPMACROS_H__
#include "cocos2d.h"
#define DESIGN_RESOLUTION_480X320 0
#define DESIGN_RESOLUTION_480X800 1
#define DESIGN_RESOLUTION_1024X768 2
#define DESIGN_RESOLUTION_1280X800 3
#define DESIGN_RESOLUTION_2048X1536 4
/* If you want to switch design resolution, change next line */
#define TARGET_DESIGN_RESOLUTION_SIZE DESIGN_RESOLUTION_1280X800
typedef struct tagResource
{
cocos2d::CCSize size;
char directory[100];
}Resource;
static Resource smallResource = { CCSizeMake(480, 320), "iphone" };
static Resource mysmallResource = { CCSizeMake(800, 480), "iphone" };
static Resource mediumResource = { CCSizeMake(1024, 768), "ipad" };
static Resource myResource = { CCSizeMake(1280, 800), "ipad" };
static Resource largeResource = { CCSizeMake(2048, 1536), "ipadhd" };
#if (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_480X320)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(480, 320);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_480X800)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(800, 480);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_1024X768)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(1024, 768);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_2048X1536)
static cocos2d::CCSize designResolutionSize = cocos2d::CCSizeMake(2048, 1536);
#elif (TARGET_DESIGN_RESOLUTION_SIZE == DESIGN_RESOLUTION_1280X800)
static CCSize designResolutionSize = cocos2d::CCSizeMake(1280, 800);
#else
#error unknown target design resolution!
#endif
// The font size 24 is designed for small resolution, so we should change it to fit for current design resolution
#define TITLE_FONT_SIZE (cocos2d::CCEGLView::sharedOpenGLView()->getDesignResolutionSize().width / myResource.size.width * 24)
#endif /* __APPMACROS_H__ */
now we can use this class in appdelegate.. so my appdelegate looks like...
#include "AppDelegate.h"
#include "MenuLayer.h"
#include "AppMacros.h"
#include "SimpleAudioEngine.h"
#include "cocos2d.h"
USING_NS_CC;
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate() {
}
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
glview = GLViewImpl::create("My Game");
director->setOpenGLView(glview);
}
CCLOG("%s","applicationDidFinishLaunching ");
// initialize director
// CCDirector* pDirector = CCDirector::sharedDirector();
// CCEGLView* pEGLView = CCEGLView::sharedOpenGLView();
director->setOpenGLView(glview);
// Set the design resolution
glview->setDesignResolutionSize(designResolutionSize.width,
designResolutionSize.height, kResolutionFixedWidth);
//CCSize frameSize = pEGLView->getFrameSize();
CCSize frameSize = director->getVisibleSize();
// if the frame's height is larger than the height of medium resource size, select large resource.
if (frameSize.width > myResource.size.width) {
director->setContentScaleFactor(
largeResource.size.width / designResolutionSize.width);
}
// if the frame's height is larger than the height of small resource size, select medium resource.
else if (frameSize.width > mediumResource.size.width) {
director->setContentScaleFactor(
myResource.size.width / designResolutionSize.width);
} else if (frameSize.width > mysmallResource.size.width) {
director->setContentScaleFactor(
designResolutionSize.width / mediumResource.size.width);
} else if (frameSize.width > smallResource.size.width) {
director->setContentScaleFactor(
designResolutionSize.width / mediumResource.size.width);
}
// if the frame's height is smaller than the height of medium resource size, select small resource.
else {
director->setContentScaleFactor(
designResolutionSize.width / smallResource.size.width);
}
// turn on display FPS
director->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
CCScene *pScene = MenuLayer::scene();
director->runWithScene(pScene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
CCDirector::sharedDirector()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
CocosDenshion::SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
CCDirector::sharedDirector()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
CocosDenshion::SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
i am also new to cocos2dx 3.3 . well i am using animation for blast (explosion) by using (.plist) particle effects
first you need a .plist file of animation . there is a online editor for making .plist file . you can check it out
here is link . http://www.effecthub.com/particle2dx
now you can use thiese line of code
CCParticleSystemQuad *system = CCParticleSystemQuad::create("explodeEffect.plist");
system->setTexture(CCTextureCache::sharedTextureCache()->addImage("yourplayer.png"));
system->setDuration(0.05);
system->setScale(3.0f);
system->setPosition(yourplayer->getPosition().x, yourplayer->getPosition().y);
this->addChild(system,1);
system->setAutoRemoveOnFinish(true);
this will help you

Cocos2D HD spriteWithFile displays in SD

I'm using Cocos2D 2.1 and this app is planned to be iPad only retina and non-retina. When I use spriteWithFile, and specify the filename without the -hd suffix, Cocos2D finds the image with the -hd suffix and uses it, but it displays in standard definition, meaning it doesn't scale down so it's displaying as a retina image.
In my delegate's - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method, I have the following:
CCGLView *glView = [CCGLView viewWithFrame:[window_ bounds]
pixelFormat:kEAGLColorFormatRGBA8
depthFormat:GL_DEPTH24_STENCIL8_OES
preserveBackbuffer:NO
sharegroup:nil
multiSampling:NO
numberOfSamples:0];
[glView setMultipleTouchEnabled:YES];
director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
[director_ setDisplayStats:YES];
[director_ setAnimationInterval:1.0/60];
// attach the openglView to the director
[director_ setView:glView];
// 2D projection
[director_ setProjection:kCCDirectorProjection2D];
[director_ enableRetinaDisplay:YES];
// // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
if( ! [director_ enableRetinaDisplay:NO] )
CCLOG(#"Retina Display Not supported");
// If the 1st suffix is not found and if fallback is enabled then fallback suffixes are going to searched. If none is found, it will try with the name without suffix.
CCFileUtils *sharedFileUtils = [CCFileUtils sharedFileUtils];
[sharedFileUtils setEnableFallbackSuffixes:NO]; // Default: NO. No fallback suffixes are going to be used
[sharedFileUtils setiPadRetinaDisplaySuffix:#"-hd"];
glView.opaque = NO;
glClearColor(0.0f,0.0f,0.0f,0.0f);
//glClear(GL_COLOR_BUFFER_BIT);
// Assume that PVR images have premultiplied alpha
[CCTexture2D PVRImagesHavePremultipliedAlpha:YES];
When I add the sprite using spriteWithFile (instead of using a sprite sheet because it's only one image) I have the following code:
movingTileGroup.handleSprite1 = [CCSprite spriteWithFile:#"draggableTileGroupHandle.png"];
movingTileGroup.handleSprite1.position = ccp(x,y);
[self.theMap addChild:movingTileGroup.handleSprite1 z:13];
Update: I see when -(BOOL) enableRetinaDisplay:(BOOL)enabled is called, none of the if statements return true. Could it have to do with a scale factor setting?
-(BOOL) enableRetinaDisplay:(BOOL)enabled
{
NSLog(#"enableRetinaDisplay called");
// Already enabled ?
if( enabled && __ccContentScaleFactor == 2 ){
NSLog(#"enabled && __ccContentScaleFactor == 2 ");
return YES;
}
// Already disabled
if( ! enabled && __ccContentScaleFactor == 1 ){
NSLog(#"! enabled && __ccContentScaleFactor == 1 ");
return YES;
}
// setContentScaleFactor is not supported
if (! [__view respondsToSelector:#selector(setContentScaleFactor:)]){
NSLog(#"setContentScaleFactor is not supported");
return NO;
}
// SD device
if ([[UIScreen mainScreen] scale] == 1.0){
NSLog(#"SD device");
return NO;
}
float newScale = enabled ? 2 : 1;
[self setContentScaleFactor:newScale];
// Load Hi-Res FPS label
[[CCFileUtils sharedFileUtils] buildSearchResolutionsOrder];
[self createStatsLabel];
return YES;
}
I am assuming you are using Spritebuilder to generate sprites , if that is so you need to specify the default size of the image in the spritebuilder software, this can be done by clicking on the image which is showing the problem and then on the left sidebar or panel select the image size as "default" and it will automatically scale to the required size...
If this doesn't solves your problem, Do let me know... regards...

Cocos 2d - launch image resizes from 568h to #2x on iPhone 5 automatically?

Hello! I am running the most basic Hello World app using Cocos2d, literally unmodified from the most basic cocos2d template in Xcode.
When I start the simulator the launch image for iPhone 5 automatically loads - however after a few seconds the launch image switches to the default#2x for iPhone 4, so there are two small back stripes of unused space on either side of the launch image.
Why is this so? And how can I make it so that the launch image doesn't automatically switch to smaller version for iPhone 4 after a few seconds?
Thanks
In IntroLayer.mm add this code:
CCSprite *background;
if( IS_IPAD)
{
if(IS_RETINA)
background = [CCSprite spriteWithFile:#"Default-Portrait#2x~ipad.png"];
else
background = [CCSprite spriteWithFile:#"Default-Portrait~ipad.png"];
}
else
{
if(IS_IPHONE5)
background = [CCSprite spriteWithFile:#"Default-568h#2x.png"];
else
{
if(IS_RETINA)
background = [CCSprite spriteWithFile:#"Default#2x.png"];
else
background = [CCSprite spriteWithFile:#"Default.png"];
}
}
Used Macro:
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPHONE5 (IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0f)
#define IS_RETINA ([[UIScreen mainScreen] respondsToSelector:#selector(displayLinkWithTarget:selector:)] && ([UIScreen mainScreen].scale == 2.0))

cocos2d + GKMatchmakerViewController causes portrait mode

I'm implementing Game Kit in a cocos2d game project.
The game is landscape orientation only. And so should gamekit also be.
When I present the gamekit modal viewcontroller for matchmaking, it displays in landscape. But the underlying cocos2d CCLayer becomes portrait.
The rootViewContollers orientation code looks like this:
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
//
// There are 2 ways to support auto-rotation:
// - The OpenGL / cocos2d way
// - Faster, but doesn't rotate the UIKit objects
// - The ViewController way
// - A bit slower, but the UiKit objects are placed in the right place
//
#if GAME_AUTOROTATION==kGameAutorotationNone
//
// EAGLView won't be autorotated.
// Since this method should return YES in at least 1 orientation,
// we return YES only in the Portrait orientation
//
return ( interfaceOrientation == UIInterfaceOrientationPortrait );
#elif GAME_AUTOROTATION==kGameAutorotationCCDirector
//
// EAGLView will be rotated by cocos2d
//
// Sample: Autorotate only in landscape mode
//
if( interfaceOrientation == UIInterfaceOrientationLandscapeLeft ) {
[[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeRight];
} else if( interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
[[CCDirector sharedDirector] setDeviceOrientation: kCCDeviceOrientationLandscapeLeft];
}
// Since this method should return YES in at least 1 orientation,
// we return YES only in the Portrait orientation
return ( UIInterfaceOrientationIsLandscape(interfaceOrientation) );
#elif GAME_AUTOROTATION == kGameAutorotationUIViewController
//
// EAGLView will be rotated by the UIViewController
//
// Sample: Autorotate only in landscpe mode
//
// return YES for the supported orientations
return ( UIInterfaceOrientationIsLandscape( interfaceOrientation ) );
#else
#error Unknown value in GAME_AUTOROTATION
#endif // GAME_AUTOROTATION
// Shold not happen
return NO;
}
It makes no difference if I define GAME_AUTOROTATION to kGameAutorotationUIViewController or kGameAutorotationCCDirector or kGameAutorotationNone
So I believe I have found a fix.
In my AppDelegate I made these changes:
//[window addSubview: viewController.view];
[window setRootViewController:viewController];
Then orientation worked perfectly on iOS6, but on iOS versions prior to iOS6 the width and height of the window size was reversed, and caused issues for the game. I solved that by adding a blank scene before running my normal scene, because the reverse size was fixed by itself when pushing a new scene. From the blank scene I ran [[CCDirector sharedDirector] replaceWithScene:[Game scene]]; after a delay, and it works now.

Is object remain fixed when scrolling background in cocos2d

I have one question when infinite background scrolling is done, is the object remain fixed(like doodle in doodle jump, papy in papi jump) or these object really moves.Is only background move or both (background and object )move.plz someone help me.I am searching for this solution for 4/5 days,but can't get the solution.So plz someone help me. And if object does not move how to create such a illusion of object moving.
If you add the object to the same layer as the scrolling background, then it will scroll as the background scrolls.
If your looking for an effect like the hero in doodle jump, you may want to look at having two or more layers in a scene.
Layer 1: Scrolling Background Layer
Layer 2: Sprite layer
SomeScene.m
CCLayer *backgroundLayer = [[CCLayer alloc] init];
CCLayer *spriteLayer= [[CCLayer alloc] init];
[self addChild:backgroundLayer z:0];
[self addChild:spriteLayer z:1];
//Hero stays in one spot regardless of background scrolling.
CCSprite *squidHero = [[CCSprite alloc] initWithFile:#"squid.png"];
[spriteLayer addChild:squidHero];
If you want objects to scroll with the background add it to the background layer:
//Platform moves with background.
CCSprite *bouncePlatform= [[CCSprite alloc] initWithFile:#"bouncePlatform.png"];
[backgroundLayer addChild:bouncePlatform];
Another alternative is to use a CCFollow action. You would code as if the background is static (which it will be) and the player is moving (which it will be), but add a CCFollow action to the player. This essentially moves the camera so that it tracks your player.
You can also modify the classes so that you can get the CCFollow action to follow with an offset (i.e., so the player is not in the middle of the screen) as well as to have a smoothing effect to it, so that when the player moves, the follow action is not jerky. See the below code:
*NOTE I am using cocos2d-x, the c++ port. The methods are similar in cocos2d, and you should be able to modify these to fit the cocos2d syntax. Or search around -- I found these for cocos2d and then ported to c++.
//defines the action to constantly follow the player (in my case, "runner.p_sprite is the sprite pointing to the player)
FollowWithOffset* followAction = FollowWithOffset::create(runner.p_sprite, CCRectZero);
runAction(followAction);
And separately, I have copied the class definition for CCFollow to create my own class, CCFollowWithAction. This also has a smoothing effect (you can look this up more online) so that when the player moves, the actions are not jerky. I modified "initWithTarget," to take into account an offset, and "step," to add a smoothing action. You can see the modifications in the comments below.
bool FollowWithOffset::initWithTarget(CCNode *pFollowedNode, const CCRect& rect/* = CCRectZero*/)
{
CCAssert(pFollowedNode != NULL, "");
pFollowedNode->retain();
m_pobFollowedNode = pFollowedNode;
if (rect.equals(CCRectZero))
{
m_bBoundarySet = false;
}
else
{
m_bBoundarySet = true;
}
m_bBoundaryFullyCovered = false;
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
m_obFullScreenSize = CCPointMake(winSize.width, winSize.height);
//m_obHalfScreenSize = ccpMult(m_obFullScreenSize, 0.5f);
m_obHalfScreenSize = CCPointMake(m_obFullScreenSize.x/2 + RUNNER_FOLLOW_OFFSET_X,
m_obFullScreenSize.y/2 + RUNNER_FOLLOW_OFFSET_Y);
if (m_bBoundarySet)
{
m_fLeftBoundary = -((rect.origin.x+rect.size.width) - m_obFullScreenSize.x);
m_fRightBoundary = -rect.origin.x ;
m_fTopBoundary = -rect.origin.y;
m_fBottomBoundary = -((rect.origin.y+rect.size.height) - m_obFullScreenSize.y);
if(m_fRightBoundary < m_fLeftBoundary)
{
// screen width is larger than world's boundary width
//set both in the middle of the world
m_fRightBoundary = m_fLeftBoundary = (m_fLeftBoundary + m_fRightBoundary) / 2;
}
if(m_fTopBoundary < m_fBottomBoundary)
{
// screen width is larger than world's boundary width
//set both in the middle of the world
m_fTopBoundary = m_fBottomBoundary = (m_fTopBoundary + m_fBottomBoundary) / 2;
}
if( (m_fTopBoundary == m_fBottomBoundary) && (m_fLeftBoundary == m_fRightBoundary) )
{
m_bBoundaryFullyCovered = true;
}
}
return true;
}
void FollowWithOffset::step(float dt)
{
CC_UNUSED_PARAM(dt);
if(m_bBoundarySet){
// whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased
if(m_bBoundaryFullyCovered)
return;
CCPoint tempPos = ccpSub( m_obHalfScreenSize, m_pobFollowedNode->getPosition());
m_pTarget->setPosition(ccp(clampf(tempPos.x, m_fLeftBoundary, m_fRightBoundary),
clampf(tempPos.y, m_fBottomBoundary, m_fTopBoundary)));
}
else{
//custom written code to add in support for a smooth ccfollow action
CCPoint tempPos = ccpSub( m_obHalfScreenSize, m_pobFollowedNode->getPosition());
CCPoint moveVect = ccpMult(ccpSub(tempPos,m_pTarget->getPosition()),0.25); //0.25 is the smooth constant.
CCPoint newPos = ccpAdd(m_pTarget->getPosition(), moveVect);
m_pTarget->setPosition(newPos);
}
}