I want to use UITextField in Cocos2d, so I wrote the following code:
// In HelloWorldLayer...
-(id) init
{
if( self=[super init] )
{
CGSize winSize = [[CCDirector sharedDirector] winSize];
UIView *view = [[CCDirector sharedDirector] openGLView];
// CGRect rect = CGRectMake(60.0, 45.0, 360.0, 25.0);
CGPoint pos1 = ccp( 60.0, winSize.height - 45.0 );
CGPoint pos2 = ccp( 360.0, 25.0 );
pos1 = [[CCDirector sharedDirector] convertToUI:pos1];
pos2 = [[CCDirector sharedDirector] convertToUI:pos2];
// UITextField *_tField; it is declared in field
_tField = [[UITextField alloc] initWithFrame:CGRectMake(pos1.x, pos1.y, pos2.x, pos2.y)];
_tField.backgroundColor = [UIColor whiteColor];
_tField.borderStyle = UITextBorderStyleRoundedRect;
_tField.returnKeyType = UIReturnKeyDone;
_tField.delegate = self;
[view addSubview:_tField];
}
return self;
}
Now I have problem like this:
http://serviceapi.nmv.naver.com/flash/convertIframeTag.nhn?vid=F25D1799886DD32FDA54463C2458197E492A&outKey=V1269fde60a3180c7d50216a83d22b478817df9b6060a511adffa16a83d22b478817d&width=720&height=438
How can I solve this problem...?
By the problem, do you mean why the text is not being written horizontally?
Because the text is actually written horizontally, maybe you have something else that is affecting the code.
Related
I have An Array inside my touches began method (I would like to be able to touch the sprite
and for it to NSlog the touch) is there something im forgetting to do or am doing something wrong?
I can log the touch on the screen but when I touch the bubbles nothing happens.
any help would be great.
-(id) init
{
if((self=[super initWithColor:ccc4(10, 10, 10,10)]) ) //sand 101, 116, 88
{
size = [[CCDirector sharedDirector] winSize];
self.touchEnabled = YES;
//other stuff here
Bubble01 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:BubbleAnswerBubble_1_IndexValue]]];
Bubble02 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:BubbleAnswerBubble_2_IndexValue]]];
Bubble03 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:BubbleAnswerBubble_3_IndexValue]]];
Bubble04 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:BubbleAnswerBubble_4_IndexValue]]];
Bubble05 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:BubbleAnswerBubble_5_IndexValue]]];
Bubble06 = [[Bubble alloc]initWithBubbleWithLabel:#"_Bubble.png" opacity:255 gloss:#"_Bubble_overlay.png" posX:0 posY:0 data:[NSString stringWithFormat:#"%#", [Sortingarray objectAtIndex:AnswerBubble_6_IndexValue]]];
//other stuff here
}
return self;
}
touchesbegan
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//set up touches
NSSet *allTouch = [event allTouches];
UITouch *touch = [[allTouch allObjects]objectAtIndex:0];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector]convertToGL:location];
//log if touches are working if I touch the screen area
NSLog(#"touches screen");
//create an array from bubble class (CCSprites with labels,
//I need to be able to determine which sprite was touched and run an action on it)
BubbleArray = [[NSMutableArray alloc]initWithObjects:Bubble01,
Bubble02,
Bubble03,
Bubble04,
Bubble05,
Bubble06,
nil];
for(int i = 0; i < [BubbleArray count]; i++)
{
Bubble *sprite = (Bubble *)[BubbleArray objectAtIndex:i];
//create a rect to find the position and size of the sprite
//BackBubble is a sprite that i'm using to detect the content size
CGRect targetRect = CGRectMake(
sprite.BackBubble.position.x - (sprite.BackBubble.contentSize.width/2),
sprite.BackBubble.position.y - (sprite.BackBubble.contentSize.height/2),
sprite.BackBubble.contentSize.width,
sprite.BackBubble.contentSize.height);
//use the rect and touch location to determine hit
if(CGRectContainsPoint(targetRect, location))
//this doesn't work possibly because Bubble class is a CClayer?
//if(CGRectContainsPoint([sprite boundingBox], location))
{
selectedSprite = sprite;
NSLog(#"touches bubble sprite");
}
}
}
Any insight would be great to help me understand what i'm doing wrong.
cheers :)
new array code (getting the height and width of the sprite through the custom class
for(int i = 0; i < [DragItems count]; i++)
{
Bubble *sprite = (Bubble *)[BubbleArray objectAtIndex:i];
location = [sprite convertToNodeSpace:location];
if(CGRectContainsPoint([sprite.BackBubble boundingBox], location))
{
selectedSprite = sprite;
NSLog(#"touches bubble");
}
}
Bubble.m
#import "Bubble.h"
#import "Common.h"
#define ButtonFlashTime .4
#define KBubbleColourTurqoiseBlueFlash 2323
#define ScrollSpeed 5.2f
#define DecoyTextY 5
#define DecoyTextX -2
#implementation Bubble
#synthesize BackBubble,FrontShine,BubbleLabel,startX,startY,currentY,currentX,isNotTouchActivated,myInt,bubblespeed,tagNumber; //isTouched
-(id)init
{
self=[super init];
{
//touches
[[[CCDirector sharedDirector] touchDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
isNotTouchActivated = false;
isTouched = NO;
bubblespeed = 0;
//start scrolling
[self MoveWithoutProblem];
[self setAnchorPoint:ccp(0.5,0.5)];
BackBubble = [CCSprite spriteWithSpriteFrameName:Bubblepng];
BackBubble.position = ccp(X,Y);
[BackBubble setAnchorPoint:ccp(0,0)];
[self addChild: BackBubble z:5];
NSLog(#"BackBubble, %f %f",BackBubble.position.x,BackBubble.position.y);
//other code here
[self setContentSize:[BackBubble boundingBox].size];
}
return self;
}
-(BOOL) isTouchOnSprite:(CGPoint)touch{
CGPoint local = [self convertToNodeSpace:touch];
CGRect r = self.boundingBox;
r.origin = CGPointZero;
Boolean b = CGRectContainsPoint( r, local );
//CCLOG(#"touch %f : %f : %d",touch.x,touch.y,b);
if (b) {
return YES;
}else {
return NO;
}
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
if([self isTouchOnSprite:touchPoint]){
//CGPoint move = [self convertTouchToNodeSpace:touch];
isNotTouchActivated = TRUE;
//isTouched = YES;
//NSLog(#"isTouched = %#", self.isTouched ? #"YES" : #"NO");
currentX = touchPoint.x;
currentY = touchPoint.y;
self.position = touchPoint;
return YES;
}
// NSLog(#"isTouched = %#", self.isTouched ? #"YES" : #"NO");
return NO;
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
if (isNotTouchActivated) {
currentX = touchPoint.x;
currentY = touchPoint.y;
self.position = touchPoint;
}
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
isNotTouchActivated = FALSE;
//isTouched = NO;
}
-(void)MoveWithoutProblem{
CGSize size = [[CCDirector sharedDirector] winSize];
int MaxHeightofBubbles = 350;
int minHeightofBubbles = 150;
int RandomNumber = [self generateRandomNumberBetweenMin:minHeightofBubbles Max:MaxHeightofBubbles];
float ConvertedRandom = [[NSNumber numberWithInt: RandomNumber] floatValue];
int MaxWidthofBubbles = 0;
int minWidthofBubbles = 900;
int RandomNumber02 = [self generateRandomNumberBetweenMin:MaxWidthofBubbles Max:minWidthofBubbles];
float ConvertedRandom02 = [[NSNumber numberWithInt: RandomNumber02] floatValue];
startX = ConvertedRandom02;
startY = ConvertedRandom;
currentX = startX+myInt;
currentY = startY;
self.position = ccp(startX,startY);
[self schedule:#selector(startMoving)];
}
-(void)startMoving{
if (!isNotTouchActivated) {
currentX+=bubblespeed;
[self setPosition:ccp(currentX,currentY)];
}
if (self.position.x >= 1024+50) {
//NSLog(#"off screen");
isrestartscrolling = YES;
}
if (isrestartscrolling == YES) {
//[self RandomYPOs];
[self scheduleOnce:#selector(newRandomX) delay:0.2];
isrestartscrolling = NO;
}
}
#end
Your code is a little hard to read but your immediate problem to why the touch doesn't work is because you are assuming your layer (Bubble) has a content width and height. If you did not set this, it wouldn't have it which is why your commented out line for [sprite boundingBox] does not work. Try [sprite.BackBubble boundingBox]. Adding items to a layer does not adjust that layer's content size automatically.
Another thing you can try is to add:
location = [sprite convertToNodeSpace:location];
If your bubble layer or that back bubble is moved at any point then simply adding the back bubble's position to a CGRect is not likely to work. Try the first idea first then try this if it doesn't work.
Hope this helped you Natalie.
I want to create a toolbar (initially hidden) with items that can be dragged. If a button is tapped, the toolbar will appear buttom-up (just like the animation of keyboard). I just like to ask how to do it in cocos2d.
Thanks for the response!
I used this code for drawer open and close.
-(void)showMyCocos2DDrawer
{
CGSize s = [[CCDirector sharedDirector] winSize];
self.position = ccp(-s.width,0.0f); //do this in ur init method :)
CGPoint pos =ccp(0.0f, 0.0f );
id moveTo = [CCMoveTo actionWithDuration:0.5f position:pos];
id calFun = [CCCallFunc actionWithTarget:self selector:#selector(animDone)];
id seq = [CCSequence actions:moveTo, calFun, nil];
[self runAction:seq];
}
-(void)hideCocos2DDrawer
{
CGSize s = [[CCDirector sharedDirector] winSize];
CGPoint pos =ccp(-s.width, 0.0f);
id moveTo = [CCMoveTo actionWithDuration:0.3f position:pos];
id calFun = [CCCallFunc actionWithTarget:self selector:#selector(goBack)];
id seq = [CCSequence actions:moveTo, calFun, nil];
[self runAction:seq];
}
-(void) animDone
{
//write in code here..
}
-(void)goBack
{
//write out code here..
}
So within a CCLayer I am adding an ImagePicker / Camera to the openGLView and then a UIButton - all good, but now I want to add a CCLabel (and in the future CCSprites) on top of those elements.
uip = [[UIImagePickerController alloc] init];
uip.sourceType = UIImagePickerControllerSourceTypeCamera;
uip.showsCameraControls = NO;
uip.toolbarHidden = YES;
uip.navigationBarHidden = YES;
uip.wantsFullScreenLayout = YES;
uip.cameraViewTransform = CGAffineTransformScale(uip.cameraViewTransform, CAMERA_TRANSFORM, CAMERA_TRANSFORM);
[[[CCDirector sharedDirector] openGLView] addSubview:uip.view];
arrowButton = [UIButton buttonWithType:UIButtonTypeCustom];
[arrowButton addTarget:self
action:#selector(arrowButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];
UIImage *imgNormal = [UIImage imageNamed:#"btn_next_norm.png"];
[arrowButton setImage:imgNormal forState:UIControlStateNormal];
UIImage *imgPressed = [UIImage imageNamed:#"btn_next_pressed.png"];
[arrowButton setImage:imgPressed forState:UIControlStateHighlighted];
arrowButton.frame = CGRectMake(screenSize.width - 48.0, screenSize.height - 37.0, 48.0, 37.0);
[[[CCDirector sharedDirector] openGLView] addSubview:arrowButton];
CCLabelTTF* label = [CCLabelTTF labelWithString:#"Experience 1" fontName:#"Arial" fontSize:32];
label.color = ccc3(0, 0, 0);
CGSize size = [[CCDirector sharedDirector] winSize];
label.position = CGPointMake(size.width / 2, size.height / 2);
// [[[CCDirector sharedDirector] openGLView] addSubview:labe]; cant add to openGLView
You need to addSubview UIView components under the openGLView as the following,
[[[CCDirector sharedDirector] openGLView].superview addSubview:arrowButton];
And then, openGLView should be transparent. "Displaying an EAGLView with transparent background on a UIImageView"
EDIT:
moving the Cocos on top of the UIImagePickerController
Ok, how about the following? addSubview the cocos2d view (openGLView) on cameraOverlayView of UIImagePickerController.
[[[CCDirector sharedDirector] openGLView].superview addSubview:uip.view];
[[[[CCDirector sharedDirector] openGLView] removeFromSuperview];
uip.cameraOverlayView = [[CCDirector sharedDirector] openGLView];
Also, you need Making Cocos2d Transparent.
I need help figuring out the rotation of a sprite with my finger. The sprite is rotating fine but on the initial touch of my finger it somehow rotates by a few degrees by itself.
Also the rotations only work when the finger is rotated around the center of the sprite.
I am trying to simulate the bicycle wheel and have a gear sprite and a pedal sprite as a child of the gear sprite. I want the bicycle wheel to rotate as I touch the pedal and rotate it. I haven't got that far yet. Right now I am trying to figure out how to get rid of the initial shift the gear makes.
Here is the complete code
#import "BicycleScene.h"
#implementation BicycleScene
+(id) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
BicycleScene *layer = [BicycleScene node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
if ((self=[super init])) {
CGSize winSize = [[CCDirector sharedDirector] winSize];
//place the bicycle sprite
bicycleSprite = [CCSprite spriteWithFile:#"bike_gear.png"];
bicycleSprite.position = ccp(bicycleSprite.contentSize.width/2 + 100, winSize.height/2);
[self addChild:bicycleSprite z:1];
//place the pedal sprite
pedalSprite = [CCSprite spriteWithFile:#"bike_pedal.png"];
[bicycleSprite addChild:pedalSprite z:1];
pedalSprite.position = ccp(150, 15);
//enable touch
self.isTouchEnabled = YES;
[self schedule:#selector(gameLoop:) interval:.1/100];
}
return self;
}
-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"Touch begun");
}
-(void)gameLoop:(ccTime) dt{
bicycleSprite.rotation = cocosAngle;
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(#"Touch moved");
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
CGPoint previousLocation = [touch previousLocationInView:[touch view]];
CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
CGPoint previousTouchingPoint = [[CCDirector sharedDirector] convertToGL:previousLocation];
CGPoint vector = ccpSub(touchingPoint, bicycleSprite.position);
CGFloat rotateAngle = -ccpToAngle(vector);
previousAngle = cocosAngle;
cocosAngle = CC_RADIANS_TO_DEGREES( rotateAngle);
//bicycleSprite.rotation = cocosAngle;
}
#end
I am slightly confused if the line:
CGPoint vector = ccpSub(touchingPoint, bicycleSprite.position);
should actually be:
CGPoint vector = ccpSub(touchingPoint, previousTouchingPoint );
I tried that as well but it didn't work.
I have also uploaded my complete xcodeproj to 4shared for anyone who wants to take a look here: http://www.4shared.com/file/5BaeW4oe/Healthy.html
#interface MainScene : CCLayer {
CCSprite *dial;
CGFloat dialRotation;
}
+ (id)scene;
#end
---------------------------------
#implementation MainScene
+ (id)scene
{
CCScene *scene = [CCScene node];
CCLayer *layer = [MainScene node];
[scene addChild:layer];
return scene;
}
- (id)init
{
if((self = [super init])) {
CCLOG(#"MainScene init");
CGSize size = [[CCDirector sharedDirector]winSize];
dial = [CCSprite spriteWithFile:#"dial.png"];
dial.position = ccp(size.width/2,dial.contentSize.height/2);
[self addChild:dial];
self.isTouchEnabled = YES;
[self scheduleUpdate];
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)update:(ccTime)delta
{
dial.rotation = dialRotation;
}
- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
//acquire the previous touch location
CGPoint firstLocation = [touch previousLocationInView:[touch view]];
CGPoint location = [touch locationInView:[touch view]];
//preform all the same basic rig on both the current touch and previous touch
CGPoint touchingPoint = [[CCDirector sharedDirector] convertToGL:location];
CGPoint firstTouchingPoint = [[CCDirector sharedDirector] convertToGL:firstLocation];
CGPoint firstVector = ccpSub(firstTouchingPoint, dial.position);
CGFloat firstRotateAngle = -ccpToAngle(firstVector);
CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);
CGPoint vector = ccpSub(touchingPoint, dial.position);
CGFloat rotateAngle = -ccpToAngle(vector);
CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);
//keep adding the difference of the two angles to the dial rotation
dialRotation += currentTouch - previousTouch;
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
EDIT: I am sorry I can't get this to stay in code mode. But this is the solution and it should be easy to implement in your code. cheers!
In ccTouchesBegan, use the same code as what you've got in ccTouchesMoved to determine the angle, then move to that angle using CCRotateTo. You will need some handling of the user moving his finger while CCRotateTo is active, perhaps stopping the current action and kicking off another one to move to the new angle.
I am a newbie at Cocos2D and i'm just getting started. I have set up a scene, and I have to change the color of a line in Cocos2D. Please can anyone help me out with this? Any help will be appreciated.
This should work:
-(id) init{
if((self = [super init])){
//CGSize winSize = [[CCDirector sharedDirector] winSize];
naughtytoucharray = [[NSMutableArray alloc] init];
self.isTouchEnabled = YES;
CCMenuItem *starMenuItem = [CCMenuItemImage itemFromNormalImage:#"ButtonStar.png" selectedImage:#"ButtonStarSel.png"
target:self selector:#selector(starButtonTapped:)];
CCMenuItem *starMenuItem1 = [CCMenuItemImage itemFromNormalImage:#"ButtonPlus.png" selectedImage:#"ButtonPlusSel.png"
target:self selector:#selector(starButtonTapped1:)];
CCMenuItem *menuItem1 = [CCMenuItemImage itemFromNormalImage:#"Button1.png" selectedImage:#"Button1Sel.png" target:self selector:#selector(button1Tapped:)];
CCMenuItem *menuItem2 = [CCMenuItemImage itemFromNormalImage:#"Button2.png" selectedImage:#"Button2Sel.png" target:self selector:#selector(button2Tapped:)];
CCMenuItem *menuItem3 = [CCMenuItemImage itemFromNormalImage:#"Button3.png" selectedImage:#"Button3Sel.png" target:self selector:#selector(button3Tapped:)];
_scoreLabel = [CCLabelTTF labelWithString:#" MyScore" dimensions:CGSizeMake(150, 30) alignment:UITextAlignmentLeft fontName:#"Arial" fontSize:15];
_scoreLabel.color = ccc3(255, 0, 0);
[_scoreLabel setPosition:ccp(80, 300)];
CCMenu *starMenu = [CCMenu menuWithItems:starMenuItem, nil];
CCMenu *starMenu1 = [CCMenu menuWithItems:starMenuItem1, nil];
CCRadioMenu *radioMenu = [CCRadioMenu menuWithItems:menuItem1, menuItem2, menuItem3, nil];
starMenuItem.position = ccp(60, 60);
starMenuItem1.position = ccp(60, 120);
radioMenu.position = ccp(120, 120);
[radioMenu alignItemsVertically];
radioMenu.selectedItem_ = menuItem1;
[menuItem1 selected];
starMenu.position = CGPointZero;
starMenu1.position = CGPointZero;
[self addChild:starMenu];
[self addChild:starMenu1];
[self addChild:radioMenu];
[self addChild:_scoreLabel];
}
[_scoreLabel setString:[NSString stringWithFormat:#"MyScore: %d", score]];
return self;
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint new_location = [touch locationInView:[touch view]];
new_location = [[CCDirector sharedDirector] convertToGL:new_location];
CGPoint oldTouchLocation = [touch previousLocationInView:touch.view];
oldTouchLocation = [[CCDirector sharedDirector] convertToGL:oldTouchLocation];
oldTouchLocation = [self convertToNodeSpace:oldTouchLocation];
[naughtytoucharray addObject:NSStringFromCGPoint(new_location)];
[naughtytoucharray addObject:NSStringFromCGPoint(oldTouchLocation)];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
exit(0);
NSLog(#"exit");
}
else if(buttonIndex == 1)
{
//CCScene *scene = [CCScene node];
[[CCDirector sharedDirector] replaceScene:[GameScene scene1]];
NSLog(#"Play again");
}
}
-(void)draw
{
glEnable(GL_LINE_SMOOTH);
for (int i = 0; i < [naughtytoucharray count]; i+=2)
{
CGPoint start = CGPointFromString([naughtytoucharray objectAtIndex:i]);
CGPoint end = CGPointFromString([naughtytoucharray objectAtIndex:i+1]);
ccDrawLine(start, end);
glColor4ub(200, 120, 120, 255);