objective c - How to add +1 to the label every time sprite is touched? -


i developing game using cocos2d 3.0. have sprite. i'd add +1 label every time sprite touched( score).

-(void) touchbegan:(uitouch *)touch withevent:(uievent *)event {  cgpoint location = [touch locationinview: [touch view]]; cgpoint convertedlocation = [[ccdirector shareddirector] converttogl: location]; cgpoint convertednodespacepoint = [self converttonodespace:convertedlocation];    if (cgrectcontainspoint([_sprite boundingbox],convertednodespacepoint)) {   label = [cclabelttf labelwithstring:@"1" fontname:@"verdana-bold" fontsize:23.0f];  label.position = ccp(_contentsize.width - _contentsize.width/20,_contentsize.height - _contentsize.height/20);   [self addchild:label ];  }} 

edited according answers :

in @implementation:

long score; cclabelttf *label; 

in - (id)init:

    label= [cclabelttf labelwithstring:@"" fontname:@"verdana-bold" fontsize:23.0f];     label.position = ccp(_contentsize.width - _contentsize.width/20,_contentsize.height - _contentsize.height/20);      [self addchild:label ]; 

and :

-(void) touchbegan:(uitouch *)touch withevent:(uievent *)event {  cgpoint location = [touch locationinview: [touch view]]; cgpoint convertedlocation = [[ccdirector shareddirector] converttogl: location]; cgpoint convertednodespacepoint = [self converttonodespace:convertedlocation];    if (cgrectcontainspoint([_abce boundingbox],convertednodespacepoint)) {     score++;     [label setstring:[nsstring stringwithformat:@"%ld",score ] ];              } 

that doesn't work. there no label there.

edited(2): figured out, how right. ok, except

 label= [cclabelttf labelwithstring:@"" fontname:@"verdana-bold" fontsize:23.0f];         label.position = ccp(_contentsize.width - _contentsize.width/20,_contentsize.height - _contentsize.height/20);          [self addchild:label ]; 

it should not placed in init method! placed in onenter method. works fine

in code adding new label on every touch on sprite. code part alok rao said. add cclabelttf *label variable (may in init() or so) how did _sprite. , take class variable int counter.

-(void) touchbegan:(uitouch *)touch withevent:(uievent *)event {     cgpoint location = [touch locationinview: [touch view]];    cgpoint convertedlocation = [[ccdirector shareddirector] converttogl: location];    cgpoint convertednodespacepoint = [self converttonodespace:convertedlocation];     if (cgrectcontainspoint([_sprite boundingbox],convertednodespacepoint)) {       counter++;        [label setstring:[@(counter) stringvalue]; // or can [label setstring:[nsstring stringwithformat:@"%d",counter]]; 

}}


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -