Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user input using cocos2d

I am looking to prompt the user to enter his/her name at the beginning of a game I am building.

What is the best way to get input from the user in cocos2d?

Thank you, Joey

like image 808
Joey Avatar asked Feb 18 '23 13:02

Joey


1 Answers

Cocos2d doesn't have any text input controls but you can easily add UIKit controls to the scene in Cocos2d 2.0

[[CCDirector sharedDirector] view] addSubview:myTextField];

You can use a UIAlertView with a text field embedded.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"Done" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
//[alert release]; If not using ARC

To receive the events back from the UIAlertView you implement the UIAlertViewDelegate. In your header file add the delegate protocol to your interface

@interface BTMyScene : CCLayer <UIAlertViewDelegate>

Then in your implementation file add any of the methods from the delegate protocol you want to receive notifications for. You probably want this one

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
     UITextField *textField = [alertView textFieldAtIndex:0];
     NSString *name = textField.text;
}

I recommend reading the documentation for UIAlertView and UIAlertViewDelegate. You will see all the available methods that you can use.

like image 137
Ben Trengrove Avatar answered Feb 28 '23 10:02

Ben Trengrove