Sakib Ahammed Sakib Ahammed - 6 months ago 18
Objective-C Question

set customize attribute value in a sprite in cocos2d ios

I want to make a puzzle game by

cocos2d ios
. For that, I want to set value in customized attribute. Like:

In cocos2d js:(value, power, picked attribute)

var sprite = cc.Sprite.createWithSpriteFrame("res/dice.png" ,tileImage[0][randomTile]);
sprite.val = randomTile;
sprite.power = 0;
sprite.picked = false;
sprite.setScale(0.55);
this.addChild(sprite,1);
sprite.setPosition(col*tileSize+tileSize/2,row*tileSize+tileSize/2);

tileArray[row][col] = sprite;


I want to do this in cocos2d ios. Can I do this? How?

I can create a sprite in
cocos2d ios
like:

CCSprite* ss = [CCSprite spriteWithSpriteFrame:tileImage[0][randomCandy]];
ss.anchorPoint = ccp(0.5, 0.5);
ss.scale = 0.55f*appDelegate.deviceScaleFloat*appDelegate.deviceRatinaVariable;
ss.position = ccp(layer_posX+col*tileSize+tileSize/2,layer_posY+row*tileSize+tileSize/2);
[self addChild:ss z:1];


Also I want to store this sprite in a 2d array, want to access later for finding these value, power, picked

Answer

I can do this by create a sprite object in a cocos touch class. So, my object class is:

The objectSpriteClass.h definition is:

#import "CCSprite.h"

@interface objectSpriteClass : CCSprite
{
    int value;
    int power;
    BOOL picked;

}

@property(readwrite, assign) int value, power;
@property(assign, readwrite) BOOL picked;

- (id)initWithSprite:(int)type;
@end  

And objectSpriteClass.m class definition is:

#import "objectSpriteClass.h"

@implementation objectCandy
@synthesize value, power, picked;
- (id)initWithSprite:(int)type
{
    if( (self=[super init] ))
{
    value = 0; // set value
    power = 1; // set power
    picked = NO; // set
    CCTexture *texture=[CCTexture textureWithFile:[NSString stringWithFormat:@"gem-%d.png",type]];
    if( texture ) {
        CGRect rect = CGRectZero;
        rect.size = texture.contentSize;
        return [self initWithTexture:texture rect:rect];
    }
}
return self;
}

@end

Then you can create an object of this class Like:

objectSpriteClass *spriteArray[20];

objectCandy *Obj = [[objectCandy alloc] initWithSprite: 1];

    Obj.anchorPoint = ccp(0.5, 0.5);
    Obj.opacity = 1.0f;
    Obj.scale = 1.0f;
    Obj.position = ccp(100, 100);
    [self addChild:Obj z:1];

spriteArray[0] = Obj;
Comments