ccTouchesBegan is not working in cocos2d-android - cocos2d-android

I enabled setIsTouchEnabled(true); but i cant able to detect the touch begin and touch end in cocos2d-android.
my gamelayer is
public class GameLayer extends CCColorLayer
{
protected CCLabel _label;
public static CCScene scene()
{
CCScene scene = CCScene.node();
GameLayer layer = new GameLayer(ccColor4B.ccc4(90, 90, 255, 255));
layer.getLabel();
scene.addChild(layer);
return scene;
}
public CCLabel getLabel()
{
return _label;
}
protected GameLayer(ccColor4B color)
{
super(color);
this.setIsTouchEnabled(true);
CGSize winSize = CCDirector.sharedDirector().displaySize();
Context context = CCDirector.sharedDirector().getActivity();
_label = CCLabel.makeLabel("Tap On Me to START the game", "DroidSans", 32);
_label.setColor(ccColor3B.ccBLACK);
_label.setPosition(winSize.width/2, winSize.height/2);
addChild(_label);
}
#Override
public boolean ccTouchesBegan(MotionEvent event)
{
CGRect projectileRect = CGRect.make(_label.getPosition().x,_label.getPosition().y, _label.getContentSize().width,_label.getContentSize().height);
CGPoint touchLocation = CGPoint.ccp(event.getX(), event.getY());
CGRect targetRect = CGRect.make(event.getX(), event.getY(), 20, 20);
System.out.print(":touch Points are - :"+projectileRect+" _ - _ "+touchLocation+" _ - _ "+targetRect);
if (CGRect.intersects(projectileRect, targetRect))
{
System.err.print(": This is intersect function from App :");
}
return true;
}
#Override
public boolean ccTouchesEnded(MotionEvent event)
{
// Choose one of the touches to work with
CGPoint location = CCDirector.sharedDirector().convertToGL(CGPoint.ccp(50, 200));
System.out.printf("Got touch ", location);
CGSize winSize = CCDirector.sharedDirector().displaySize();
return true;
}
}
could any one figure me where i am going wrong? I am not getting any errors and no logs traced in logcat

Your code is good, just use System.out.println() function to output text to console instead of System.out.printf(), System.err.print(). When I have replaced them, text has appeared in console.
This:
System.out.print(":touch Points are - :"+projectileRect+" _ - _ "+touchLocation+" _ - _ "+targetRect);
change to:
System.out.println(":touch Points are - :"+projectileRect+" _ - _ "+touchLocation+" _ - _ "+targetRect);
and this:
System.err.print(": This is intersect function from App :");
change to:
System.out.println(": This is intersect function from App :");
and this too:
System.out.printf("Got touch ", location);
change to:
System.out.println("Got touch " + location);

You need to add this on the constructor :
this.setIsTouchEnabled(true);

Related

Swift 3.0 - Sprite Kit - Multitouch

I'm new to Swift SpriteKit, I want to make a game like a virtual joystick and two buttons(two nodes), I've enabled the multi-touch. However, whenever I move both virtual joystick and attack Spritenode, the virtual joystick of the button seems to be Jagging. How am I gonna separate the touches of virtual joystick from touches attackbutton
class GameScene: SKScene {
var defend : Bool = false
var attack : Bool = false
var stickMove : Bool = false
var stickEnd:Bool = false
var moveattack:Bool = false
var movedefend:Bool = false
var playermovement:Bool = true
let vj1 = SKSpriteNode(imageNamed: "vj1")
let vj2 = SKSpriteNode(imageNamed: "vj2")
let player = SKSpriteNode(imageNamed: "player")
let rotationSpeed :CGFloat = CGFloat(M_PI)
let rotationOffSet : CGFloat = -CGFloat(M_PI/2.0)
let attackvj = SKSpriteNode(imageNamed: "attackvj")
let defendvj = SKSpriteNode(imageNamed: "defendvj")
private var touchPosition: CGFloat = 0
private var targetZRotation: CGFloat = 0
override func didMove(to view: SKView) {
self.view?.isMultipleTouchEnabled = true
self.backgroundColor = SKColor.black
//position of joystick
vj1.zPosition = 1
vj1.xScale = 1.5
vj1.yScale = 1.5
self.addChild(vj1)
vj1.position = CGPoint(x: self.size.width*15/100, y:self.size.height*30/100)
vj2.zPosition = 1
vj2.xScale = 1.5
vj2.yScale = 1.5
self.addChild(vj2)
vj2.position = vj1.position
player.zPosition = 0
player.physicsBody = SKPhysicsBody(rectangleOf: player.size)
player.physicsBody!.affectedByGravity = false
player.position = CGPoint(x: self.size.width/2, y:self.size.height/2)
self.addChild(player)
attackvj.anchorPoint = CGPoint(x: 0.5, y:0.5)
attackvj.position = CGPoint(x: self.size.width*80/100, y:self.size.height*30/100)
attackvj.xScale = 2.0
attackvj.yScale = 2.0
self.addChild(attackvj)
defendvj.anchorPoint = CGPoint(x: 0.5, y:0.5)
defendvj.position = CGPoint(x: self.size.width*90/100, y:self.size.height*50/100)
defendvj.xScale = 2.0
defendvj.yScale = 2.0
self.addChild(defendvj)
vj1.alpha = 0.4
vj2.alpha = 0.4
attackvj.alpha = 0.4
defendvj.alpha = 0.4
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches){
let location = touch.location(in: self)
if vj2.contains(location){
stickEnd = false
stickMove = true
}
if defendvj.contains(location){
defend = true
}
if attackvj.contains(location){
attack = true
attackvj.xScale = 2.5
attackvj.yScale = 2.5
}
if(stickMove == true && attack == true){
moveattack = true
}
if(stickMove == true && defend == true){
movedefend = true
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in (touches){
let location = touch.location(in: self)
let previousLocation = touch.previousLocation(in: self)
let v = CGVector(dx: location.x - vj1.position.x, dy: location.y - vj1.position.y)
print("locationsss" , location , "previouslocationsss", previousLocation)
let angle = atan2(v.dy, v.dx)
targetZRotation = angle + rotationOffSet
let length:CGFloat = vj1.frame.size.height / 2
let xDist:CGFloat = sin(angle - 1.57079633) * length
let yDist:CGFloat = cos(angle - 1.57079633) * length
if(stickMove == true){
if(vj1.frame.contains(location)){
vj2.position = location
}
else{
vj2.position = CGPoint(x: vj1.position.x - xDist, y: vj1.position.y + yDist)
}
if(attackvj.frame.contains(location)){//How am I gonna make this location in attackvj, not to influence my joystick location?
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if(stickMove == true && attack == false && defend == false){
let move:SKAction = SKAction.move(to: vj1.position, duration: 0.2)
move.timingMode = .easeOut
vj2.run(move)
stickEnd = true
stickMove = false
}
if(attack == true){
attack = false
attackvj.xScale = 2.0
attackvj.yScale = 2.0
moveattack = false
}
if(defend == true){
defend = false
movedefend = false
}
}
override func update(_ currentTime: TimeInterval) {
//rotation
if (stickEnd == false) {
var angularDisplacement = targetZRotation - player.zRotation
if angularDisplacement > CGFloat(M_PI) {
angularDisplacement = (angularDisplacement - CGFloat(M_PI)*2)
}
else if angularDisplacement < -CGFloat(M_PI) {
angularDisplacement = (angularDisplacement + CGFloat(M_PI)*2)
}
if abs(angularDisplacement) > rotationSpeed*(1.0/60.0){
let angularVelocity = angularDisplacement < 0 ? -rotationSpeed : rotationSpeed
player.physicsBody!.angularVelocity = angularVelocity
} else {
player.physicsBody!.angularVelocity = 0
player.zPosition = targetZRotation
}
}
else{
player.physicsBody!.angularVelocity = 0
}
//movement but use attack button to testing
if (attack == true)
{
player.position = CGPoint(x:player.position.x + cos(player.zRotation + 1.57079633),y:player.position.y + sin(player.zRotation + 1.57079633))
}
}
The problem you are facing is that you are mixing the contexts for your touches. This is making things more difficult and complicated than they need to be.
The easiest thing to do would be to make your virtual joystick a separate SKSpriteNode class that tracks its own touches and reports them. Same with the buttons - they track their own touches and report their state.
But if you want to continue with your current approach of having a high-level object track multiple touches, what you want to do is capture the context that each touch is associated with in touchesBegan, and then just update things on touchesMoved as necessary, canceling the touches in touchesEnded.
For instance, you want to associate a particular touch with the virtual joystick, because you don't want weirdness if they drag their finger off of it and over to the button, say. And you want to know exactly which touch is lifted off when the user lifts a finger.
Here's some sample code that should illustrate the process:
//
// This scene lets the user drag a red and a blue box
// around the scene. In the .sks file (or in the didMove
// function), add two sprites and name them "red" and "blue".
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
private var redTouch:UITouch?
private var blueTouch:UITouch?
override func didMove(to view: SKView) {
super.didMove(to: view)
isUserInteractionEnabled = true
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// Grab some references to the red and blue sprites.
// (They must be direct children of the scene, or the
// paths must be amended.)
guard let redBox = childNode(withName: "red") else { return }
guard let blueBox = childNode(withName: "blue") else { return }
for touch in touches {
// Get the location of the touch in SpriteKit Scene space.
let touchLocation = touch.location(in: self)
// Check to see if the user is touching one of the boxes.
if redBox.contains( touchLocation ) {
// If we already have a touch in the red box, do nothing.
// Otherwise, make this our new red touch.
redTouch = touch
} else if blueBox.contains( touchLocation ) {
// If we already have a touch in the blue box, do nothing.
// Otherwise, make this our new blue touch.
blueTouch = touch
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
// We have already established which touches are active,
// and we have already tied them to the two contexts, so
// we just need to read their current location and update
// the location of the red and blue boxes for the touches
// that are active.
if let redTouch = redTouch {
guard let redBox = childNode(withName: "red") else { return }
let location = redTouch.location(in:self)
redBox.position = location
}
if let blueTouch = blueTouch {
guard let blueBox = childNode(withName: "blue") else { return }
let location = blueTouch.location(in:self)
blueBox.position = location
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
// The parameter touches contains a list of ending touches,
// so we check the touches we are currently tracking to
// see if they are newly lifted. If so, we cancel them.
if let touch = redTouch {
if touches.contains( touch ) {
redTouch = nil
}
}
if let touch = blueTouch {
if touches.contains( touch ) {
blueTouch = nil
}
}
}
}
In the above code, we have separated out the touches on the red box and the blue box. We always know which touch is dragging the red box around and which touch is dragging the blue box around, if any. This is a simple example, but it's generalizable to your situation, where you'd have touches for the virtual joystick and each individual button.
Note that this approach works well for multitouch elements, too. If you have a map that you want to be zoomable, you can keep track of two touches so that you can compare them for pinch gestures. That way, if your pinch gesture accidentally strays over a button, you've already marked it as part of the pinch gesture, and know not to start triggering that button.
But again, a better approach would be to have a separate SKSpriteNode subclass that just tracks the joystick touches and reports its state to some higher-level manager class. You already know everything you need to know to do this - it's like what you have without all the extra checking to see if there are other buttons pressed. Same with the buttons. The only new part would be messaging "up the chain" to a manager, and that's pretty straightforward to deal with.

comparing loop element to the name of the UIbutton pressed inside the buttonpressed function

I am looping through an array of string arrays. I am comparing the element at index 0 to the title of the button pressed on the page(ideally). But I am getting an Unresolved Identifier error, which means I am doing something wrong. How Can I compare the element in the loop to the title of the button made programatically on the page. Here is my code! The issue is with the function at the bottom, in the if statement that is in the for loop. I don't know how to say 'if this index position of the element is equal too the title of the button pressed'.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var songArray: [Array<String>] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//connect to website
let url = URL(string:"*******")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print("error")
}
else
{
if let content = data
{
do
{
//download JSON data from php page, display data
let JSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String]]
print(JSON)
//Make buttons with JSON array
var buttonY: CGFloat = 20
for song in JSON {
self.songArray.append(song)
let SongButton = UIButton(frame: CGRect(x: 50, y: buttonY, width: 250, height: 30))
buttonY = buttonY + 50 // 50px spacing
SongButton.layer.cornerRadius = 10 //Edge formatting for buttons
SongButton.backgroundColor = UIColor.darkGray //Color for buttons
SongButton.setTitle("\(song[0])", for: UIControlState.normal) //button title
SongButton.titleLabel?.text = "\(song[0])"
SongButton.addTarget(self,action: #selector(self.songButtonPressed(_:)), for: UIControlEvents.touchUpInside) //button press / response
self.view.addSubview(SongButton) // adds buttons to view
}
}
catch
{
}
}
}
}
task.resume()
print(songArray)
}
func songButtonPressed(_ sender:UIButton!) { // function for buttons
for song in songArray {
if "\(song[0])" == SongButton.titleLabel?.text {
let URL = NSURL(string: "\(song[1])")
let player = AVPlayer(url: URL! as URL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
}
}
My train of thought is to loop through the array of arrays, compare index position 0 to all button titles on the page, and if it matches, plus index position 2 into the AV player. Thanks for any help or advice on the logic behind my code, I am a beginner and I know this level of programming is a bit over my head
It's most likely
for song in songArray {
// the string interpolation "\()" is redundant
if song[0] == sender.titleLabel?.text { ... }
or maybe
if song[0] == sender.title { ... }
SongButton is not related to the action method.

UICollectionViewLayout not working as expected

I followed this Custom Collection View Layout tutorial from raywenderlich.com using xcode 8 and swift 3.
When I ran the app after implementing all methods requested in the tutorial, I got the following error:
'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: {length = 2, path = 0 - 11}'
So I have added the following method into my CollectionViewFlowLayout class:
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.cache[indexPath.row]
}
This is almost working except that some cells are overlaying existing cells when scrolling down and then disappear. If I scroll up, everything is working perfectly.
I don't understand the full logic yet of this code but I have reviewed and tested it several times and I cannot understand which part of the code is triggering this behaviour.
Any idea?
import UIKit
/* The heights are declared as constants outside of the class so they can be easily referenced elsewhere */
struct UltravisualLayoutConstants {
struct Cell {
/* The height of the non-featured cell */
static let standardHeight: CGFloat = 100
/* The height of the first visible cell */
static let featuredHeight: CGFloat = 280
}
}
class UltravisualLayout: UICollectionViewLayout {
// MARK: Properties and Variables
/* The amount the user needs to scroll before the featured cell changes */
let dragOffset: CGFloat = 180.0
var cache = [UICollectionViewLayoutAttributes]()
/* Returns the item index of the currently featured cell */
var featuredItemIndex: Int {
get {
/* Use max to make sure the featureItemIndex is never < 0 */
return max(0, Int(collectionView!.contentOffset.y / dragOffset))
}
}
/* Returns a value between 0 and 1 that represents how close the next cell is to becoming the featured cell */
var nextItemPercentageOffset: CGFloat {
get {
return (collectionView!.contentOffset.y / dragOffset) - CGFloat(featuredItemIndex)
}
}
/* Returns the width of the collection view */
var width: CGFloat {
get {
return collectionView!.bounds.width
}
}
/* Returns the height of the collection view */
var height: CGFloat {
get {
return collectionView!.bounds.height
}
}
/* Returns the number of items in the collection view */
var numberOfItems: Int {
get {
return collectionView!.numberOfItems(inSection: 0)
}
}
// MARK: UICollectionViewLayout
/* Return the size of all the content in the collection view */
override var collectionViewContentSize : CGSize {
let contentHeight = (CGFloat(numberOfItems) * dragOffset) + (height - dragOffset)
return CGSize(width: width, height: contentHeight)
}
override func prepare() {
let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
var frame = CGRect.zero
var y:CGFloat = 0
for item in 0 ... (numberOfItems - 1) {
let indexPath = NSIndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.zIndex = item
var height = standardHeight
if indexPath.item == featuredItemIndex {
let yOffset = standardHeight * nextItemPercentageOffset
y = self.collectionView!.contentOffset.y - yOffset
height = featuredHeight
} else if item == (featuredItemIndex + 1) && item != numberOfItems {
let maxY = y + standardHeight
height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0)
y = maxY - height
}
frame = CGRect(x: 0, y: y, width: width, height: height)
attributes.frame = frame
cache.append(attributes)
y = frame.maxY
}
}
/* Return all attributes in the cache whose frame intersects with the rect passed to the method */
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return self.cache[indexPath.row]
}
/* Return true so that the layout is continuously invalidated as the user scrolls */
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
Just added that in the super.viewDidLoad of the view controller owning the UICollection view and it is now working as expected.
This is a quick fix and I believe there are a more appropriate way to fix this managing better the prefetching functions from IOS10.
if #available(iOS 10.0, *) {
collectionView!.prefetchingEnabled = false
}

changing the height of UITabBar in iOS7/8?

I am trying to change the height of the stock UITabBar to 44px, similar to Tweetbot's tab bar height. I've also seen a few other apps do this as well.
however, when i try to set the height it still remains the same
self.tabBar.frame.height = 40
are we not allowed to change the tab bar height? and if so what is a good alternative? using a toolbar?
It seems everybody says this can't be done easily
In your storyboard give your UITabBar a custom subclass name, then implement the subclass with the following
This tells all views that use the tab bar that it should be a certain height.
#implementation MyTabBar
-(CGSize)sizeThatFits:(CGSize)size
{
CGSize sizeThatFits = [super sizeThatFits:size];
sizeThatFits.height = 100;
return sizeThatFits;
}
#end
SomeGuy's answer above worked for me. Here's the Swift translation for anyone who may need it. I made the height close to what it seems most popular apps use.
class TabBar: UITabBar {
override func sizeThatFits(size: CGSize) -> CGSize {
var sizeThatFits = super.sizeThatFits(size)
sizeThatFits.height = 38
return sizeThatFits
}
}
For Swift 3 and xcode 8
extension UITabBar {
override open func sizeThatFits(_ size: CGSize) -> CGSize {
var sizeThatFits = super.sizeThatFits(size)
sizeThatFits.height = 80 // adjust your size here
return sizeThatFits
}
}
In your UITabBarController
- (void)viewWillLayoutSubviews {
CGRect tabFrame = self.tabBar.frame;
tabFrame.size.height = 80;
tabFrame.origin.y = self.view.frame.size.height - 80;
self.tabBar.frame = tabFrame;
}
In swift it is even simpler than all solutions suggested above by using an extensions to UITabBar, no subclassing necessary:
extension UITabBar {
override public func sizeThatFits(size: CGSize) -> CGSize {
super.sizeThatFits(size)
var sizeThatFits = super.sizeThatFits(size)
sizeThatFits.height = <Insert your height here>
return sizeThatFits
}
}
If you have auto layout enabled, you will need to override instrinsicContentSize instead
Proper usage of intrinsicContentSize and sizeThatFits: on UIView Subclass with autolayout
class TabBar: UITabBar {
override func intrinsicContentSize() -> CGSize {
var intrinsicSize = super.frame.size
intrinsicSize.height = 120
return intrinsicSize
}
}
The developer doesn't own the tabBar, the framework does. It will fight you to make sure that the tabBar stays the same height. If you want to work around this, you can make your own toolbar and add autlayout constraints to its height to force it to stay whatever height you'd like.
If you are on iOS 11 then following will help
-(CGSize)sizeThatFits:(CGSize)size
{
CGSize sizeThatFits = [super sizeThatFits:size];
sizeThatFits.height = 60;
if (#available(iOS 11.0, *)) {
UIWindow *window = UIApplication.sharedApplication.keyWindow;
CGFloat bottomPadding = window.safeAreaInsets.bottom;
sizeThatFits.height += bottomPadding;
}
return sizeThatFits;
}
Basically need to cover safe area, else tabbar height on iPhone X appears to be low.
For iOS11 and above you can use below:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
if (#available(iOS 11.0, *)) {
self.additionalSafeAreaInsets = UIEdgeInsetsMake(0, 0, 20, 0);
}
}
And for all os, create UITabBar subclass, use it in the UITabBarController and implement below method in the implementation of custom tab bar class:
-(CGSize)sizeThatFits:(CGSize)size {
CGSize sizeThatFits = [super sizeThatFits:size];
sizeThatFits.height = kBarHeight;
return sizeThatFits;
}

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.