Cocos2d 3.0 Set Portrait orientation - cocos2d-iphone

Already added below code in AppDelegate.m but still not working in portrait.
-(NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return UIInterfaceOrientationIsPortrait(interfaceOrientation);
}
Here is Xcode summary page:

Got solution. We can set orientation in setupCocos2dWithOptions.
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupCocos2dWithOptions:#{
CCSetupShowDebugStats: #(YES),
CCSetupScreenOrientation: CCScreenOrientationPortrait,
}];
return YES;
}

Related

Disable rotation for one UITabbar item

I have a uitabbarcontroller with 4 tab bar items and each tab bar item has a uinavigationcontroller.
I needed to lock the orientation of one uitabbar item only to Portrait. So i implemented the following code:
Created a custom tab bar controller and added the following code in it:
MainTabBarController.m
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// You do not need this method if you are not supporting earlier iOS Versions
return [self.selectedViewController shouldAutorotateToInterfaceOrientation:interfaceOrientation];
}
-(NSUInteger)supportedInterfaceOrientations
{
if (self.selectedViewController)
return [self.selectedViewController supportedInterfaceOrientations];
return UIInterfaceOrientationMaskPortrait;
}
-(BOOL)shouldAutorotate
{
return YES;
}
Created a custom navigation controller to use in one of the uitabbaritems and added the following code in it:
-(NSUInteger)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}
-(BOOL)shouldAutorotate
{
return YES;
}
and for the uiviewcontroller in the custom navigation controller i added the following code:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (BOOL)shouldAutorotate
{
return NO;
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
The above code works fine. My issue is, if you go to the tabbar item (whose orientation is locked to Protrait) when the device is already in Landscape mode the orientation changes to Landscape. Can anyone please help me how to solve my issue.
Thanks,
Anand.
FYI!!!
I've found a way for my problem. I added the following function to the viewcontroller for which i want the display only in protrait mode:
-(void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation]))
{
if ([[UIDevice currentDevice] respondsToSelector:#selector(setOrientation:)])
{
int orientationPortrait = UIInterfaceOrientationPortrait;
NSMethodSignature *sig = [[UIDevice currentDevice] methodSignatureForSelector:#selector(setOrientation:)];
NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig];
[invo setTarget:[UIDevice currentDevice]];
[invo setSelector:#selector(setOrientation:)];
[invo setArgument:&orientationPortrait atIndex:2];
[invo invoke];
}
}
}

Cocos2d animation resume

I've added iAP in cocos2d following the ray tutorials (but changed a few things to fit cocos2d) but after I make a transaction the console log says 2013-08-19 16:32:12.626 Game[2483:907] Buying *product* ...
2013-08-19 16:32:13.208 Game[2483:907] cocos2d: animation stopped
2013-08-19 16:32:16.690 Game[2483:907] completeTransaction...
2013-08-19 16:32:16.725 Game[2483:907] User defaults for *product* are YES
So I know the transaction works, but the game never resumes it just freezes. Is there a way to resume the game after the transaction? [[CCDirector sharedDirector]resume] doesn't work so I think it may have to do with UIAlert View. Any help? Here is my iAPHelper.mm:
#import "IAPHelper.h"
#import <StoreKit/StoreKit.h>
NSString *const IAPHelperProductPurchasedNotification
#"IAPHelperProductPurchasedNotification";
#interface IAPHelper () <SKProductsRequestDelegate, SKPaymentTransactionObserver>
#end
#implementation IAPHelper {
SKProductsRequest * _productsRequest;
RequestProductsCompletionHandler _completionHandler;
NSSet * _productIdentifiers;
NSMutableSet * _purchasedProductIdentifiers;
}
- (id)initWithProductIdentifiers:(NSSet *)productIdentifiers {
if ((self = [super init])) {
// Store product identifiers
_productIdentifiers = productIdentifiers;
[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
// Check for previously purchased products
_purchasedProductIdentifiers = [NSMutableSet set];
for (NSString * productIdentifier in _productIdentifiers) {
BOOL productPurchased = [[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier];
if (productPurchased) {
[_purchasedProductIdentifiers addObject:productIdentifier];
NSLog(#"Previously purchased: %#", productIdentifier);
} else {
NSLog(#"Not purchased: %#", productIdentifier);
}
}
}
return self;
}
- (void)requestProductsWithCompletionHandler:(RequestProductsCompletionHandler)completionHandler {
_completionHandler = [completionHandler copy];
_productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:_productIdentifiers];
_productsRequest.delegate = self;
[_productsRequest start];
}
#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
NSLog(#"Loaded list of products...");
_productsRequest = nil;
NSArray * skProducts = response.products;
for (SKProduct * skProduct in skProducts) {
NSLog(#"Found product: %# %# %0.2f",
skProduct.productIdentifier,
skProduct.localizedTitle,
skProduct.price.floatValue);
}
_completionHandler(YES, skProducts);
_completionHandler = nil;
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Failed to load list of products.");
_productsRequest = nil;
_completionHandler(NO, nil);
_completionHandler = nil;
}
- (BOOL)productPurchased:(NSString *)productIdentifier {
return [_purchasedProductIdentifiers containsObject:productIdentifier];
}
- (void)buyProduct:(SKProduct *)product {
NSLog(#"Buying %#...", product.productIdentifier);
SKPayment * payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
for (SKPaymentTransaction * transaction in transactions) {
switch (transaction.transactionState)
{
case SKPaymentTransactionStatePurchased:
[self completeTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
[self failedTransaction:transaction];
break;
case SKPaymentTransactionStateRestored:
[self restoreTransaction:transaction];
default:
break;
}
};
}
- (void)completeTransaction:(SKPaymentTransaction *)transaction {
NSLog(#"completeTransaction...");
[self provideContentForProductIdentifier:transaction.payment.productIdentifier];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
NSLog(#"restoreTransaction...");
[self provideContentForProductIdentifier:transaction.originalTransaction.payment.productIdentifier];
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
NSLog(#"failedTransaction...");
if (transaction.error.code != SKErrorPaymentCancelled)
{
NSLog(#"Transaction error: %#", transaction.error.localizedDescription);
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)provideContentForProductIdentifier:(NSString *)productIdentifier {
[_purchasedProductIdentifiers addObject:productIdentifier];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSNotificationCenter defaultCenter] postNotificationName:IAPHelperProductPurchasedNotification object:productIdentifier userInfo:nil];
NSLog(#"User defaults for %# are YES", productIdentifier);
}
- (void)restoreCompletedTransactions {
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
#end
Before you popup your alert view try running...
[[CCDirector sharedDirector] stopAnimation];
When you get a response back from the user in the alertview callback or transaction completion run...
[[CCDirector sharedDirector] startAnimation];
Cocos doesn't often play well with UIKit/Cocoa callbacks so you need to pause rendering while they do their thing. We have similar behaviour for when the app goes into background/foreground in the app delegate...
-(void) applicationDidEnterBackground:(UIApplication*)application {
[[CCDirector sharedDirector] stopAnimation];
}
-(void) applicationWillEnterForeground:(UIApplication *)application {
[[CCDirector sharedDirector] startAnimation];
}
-(void)applicationDidBecomeActive:(UIApplication *)application {
[[CCDirector sharedDirector] resume];
}
Seems we use resume inside the applicationDidBecomeActive. Can't recall the full logic there but that has seemed to work for a bunch of our projects.

Swipe Gesture used in application

I have issue regarding using swipe gesture.
Problem is that I want to perform both right and left swipe while holding click changing direction to left-right.
Can I use CCTouch methods for this condition? If yes then how can i use this? Is there another way to do this?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
...
[self createSwipeRecognizerView];
return YES;
}
-(void) createSwipeRecognizerView {
//NSLog(#"Creating Swipe Recognizer");
UIGestureRecognizer *recognizer;
recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(screenDidswipe)];
// swipeRightOnTable is the callback method in my case
swipeRecognizer = (UISwipeGestureRecognizer *)recognizer;
// select swipe direction
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
[self.navController.view addGestureRecognizer:recognizer];
recognizer.delegate = self;
[recognizer release];
}
-(BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if([[MyGame sharedGameObject].layer isKindOfClass:[MyGameScreen class]])
return YES;
return NO;
}
-(void) screenDidswipe
{
MyGame *sGame = [MyGame sharedGameObject];
if([sGame.layer isKindOfClass:[MyGameScreen class]])
{
[(MyGameScreen*)(sGame.layer) screenDidswipe];
}
}

cocos2d tap disabled when leaderboard closed on game center

I show the game center leaderboard but when I tap the done button the leaderboard close.
But I can't tap on any buttons on the screen.
Here my code :
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
CCLOG(#"leaderboardViewControllerDidFinish %#", viewController);
[viewController dismissModalViewControllerAnimated:YES];
[viewController.view removeFromSuperview];
[viewController release];
[[CCDirector sharedDirector] resume];
}
Use this code.
Cocos2D 2.0
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[app.navController dismissModalViewControllerAnimated:YES];
}
Cocos2D 1.0
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppDelegate* app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
[app.viewController dismissModalViewControllerAnimated:YES];
}
I'm using cocos2D 1.0
I'm sorry but the code you provide doesn't work.
I fixed the problem. I just comment one line.
I lost the close animation of the leaderboard but it's work.
- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
CCLOG(#"leaderboardViewControllerDidFinish %#", viewController);
[viewController.view removeFromSuperview];
[viewController release];
[[CCDirector sharedDirector] resume];
}

Integrate Gamecenter in cocos2d game

Is there any one who knows how to integrate game center in Cocos2d.
Please tell me steps so i can integrate that in my Game.
UPDATE:
I created my own Helper Class that works with all kind of Apps (also Cocos2D 1 & 2+)
https://github.com/alexblunck/ABGameKitHelper
Hi I suggest you use GKHelper Class from Steffen Itterheim! I uploaded the GKHelper.h / GKHelper.m for you: http://www.cl.ly/7ReW
Then follow these instructions:
//0.0 Add GameKit Framework to Project (Ask If you don't know how to do this ;) )
//0. Change "[window addSubview: viewController.view];" in the AppDelegate.m to:
//Do this if you're using any release of cocos2D after 0.99.5:
window.rootViewController = viewController;
//1. Add Gamekithelper.h / .m to project
//2. Include following delegate in given header:
<GameKitHelperProtocol>
//3. Add Delegate Methods to .m
//4. Add GameKitHelper to "Scene":
GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
gkHelper.delegate = self;
[gkHelper authenticateLocalPlayer];
//Adding score to leaderboard:
GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper submitScore:scoreValue category:#"LeaderboardID"];
//Adding achievement completion:
GameKitHelper *gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper reportAchievementWithID:#"AchievementID" percentComplete:100];
These are the delegate Methods that need to be added mentioned in Step #3:
#pragma mark GameKitHelper delegate methods
-(void) onLocalPlayerAuthenticationChanged
{
GKLocalPlayer* localPlayer = [GKLocalPlayer localPlayer];
CCLOG(#"LocalPlayer isAuthenticated changed to: %#", localPlayer.authenticated ? #"YES" : #"NO");
if (localPlayer.authenticated)
{
GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper getLocalPlayerFriends];
//[gkHelper resetAchievements];
}
}
-(void) onFriendListReceived:(NSArray*)friends
{
CCLOG(#"onFriendListReceived: %#", [friends description]);
GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper getPlayerInfo:friends];
}
-(void) onPlayerInfoReceived:(NSArray*)players
{
CCLOG(#"onPlayerInfoReceived: %#", [players description]);
}
-(void) onScoresSubmitted:(bool)success
{
CCLOG(#"onScoresSubmitted: %#", success ? #"YES" : #"NO");
}
-(void) onScoresReceived:(NSArray*)scores
{
CCLOG(#"onScoresReceived: %#", [scores description]);
GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper showAchievements];
}
-(void) onAchievementReported:(GKAchievement*)achievement
{
CCLOG(#"onAchievementReported: %#", achievement);
}
-(void) onAchievementsLoaded:(NSDictionary*)achievements
{
CCLOG(#"onLocalPlayerAchievementsLoaded: %#", [achievements description]);
}
-(void) onResetAchievements:(bool)success
{
CCLOG(#"onResetAchievements: %#", success ? #"YES" : #"NO");
}
-(void) onLeaderboardViewDismissed
{
CCLOG(#"onLeaderboardViewDismissed");
GameKitHelper* gkHelper = [GameKitHelper sharedGameKitHelper];
[gkHelper retrieveTopTenAllTimeGlobalScores];
}
-(void) onAchievementsViewDismissed
{
CCLOG(#"onAchievementsViewDismissed");
}
-(void) onReceivedMatchmakingActivity:(NSInteger)activity
{
CCLOG(#"receivedMatchmakingActivity: %i", activity);
}
-(void) onMatchFound:(GKMatch*)match
{
CCLOG(#"onMatchFound: %#", match);
}
-(void) onPlayersAddedToMatch:(bool)success
{
CCLOG(#"onPlayersAddedToMatch: %#", success ? #"YES" : #"NO");
}
-(void) onMatchmakingViewDismissed
{
CCLOG(#"onMatchmakingViewDismissed");
}
-(void) onMatchmakingViewError
{
CCLOG(#"onMatchmakingViewError");
}
-(void) onPlayerConnected:(NSString*)playerID
{
CCLOG(#"onPlayerConnected: %#", playerID);
}
-(void) onPlayerDisconnected:(NSString*)playerID
{
CCLOG(#"onPlayerDisconnected: %#", playerID);
}
-(void) onStartMatch
{
CCLOG(#"onStartMatch");
}
-(void) onReceivedData:(NSData*)data fromPlayer:(NSString*)playerID
{
CCLOG(#"onReceivedData: %# fromPlayer: %#", data, playerID);
}
You can go through with GamKit framework . Game center is very powerful for managing your online game and game score as well . with game center there are two types of game you can create
1: Real time matches (Real time Car racing)
2: Turn Base Matches (Online card game )
I am sharing with you link of RaywenderLich :
Real time match : http://www.raywenderlich.com/3276/game-center-tutorial-for-ios-how-to-make-a-simple-multiplayer-game-part-12
Turn Based Match http://www.raywenderlich.com/5480/beginning-turn-based-gaming-with-ios-5-part-1
Although Alexander Blunck's answer is reasonable, for earlier versions of iOS (such as 3.2) the following line will fault, which is not what you want.
window.rootViewController = viewController;
If you are going to use Steffen's code (ugh) then you might want to add a method to set the ui view controller directly rather than having it assume it can be grabbed via UIApplication.