1
votes

I am currently using cocos2dx. My testing device is ipad2 i want my sprite size to be independent of texture size because i cant afford one to one mapping. here is the example suppose i have a texture whose dimensions are 1024,1024 i want to use only portion of it from 0,0 to 300,300 i want that sprite to draw from 100,100 to 200,200 how can i acheive this

i have tried setting quad manualy but its giving a weird behaviour my quad vertices are

     quad.bl.vertices = 0,0
     quad.br.vertices = 1024,0
     quad.tr.vertices = 1024,1024
     quad.tl.vertices = 0,1024

nothing is displayed on screen

but when i change them to

     quad.bl.vertices = 0,0
     quad.br.vertices = 2048,0
     quad.tr.vertices = 2048,2048
     quad.tl.vertices = 0,2048

then portion of sprite is displayed on screen. after changing the vertices a bit it seems as if coocs 2d is assuming that the bottom left corner of ipad is at 1024, 1024 regards

1
in cocos2d-iphone ccsprite has texture and texturerect properties, the latter defines which part of the texture to draw - LearnCocos2D
but if i use texturerect then sprite size will change which isn't required - Arslan Mubashar Khan
i am able to apply the right uv by overriding the CCSprite and calling setTextureCoords manually but resizing the sprite is still not working - Arslan Mubashar Khan

1 Answers

2
votes

I think this is what you need

CCRect requiredPortion = CCRectMake(0, 0, 300, 300);
CCRect drawArea = CCRectMake(100, 100, 100, 100);

CCImage *image = new CCImage();
image->initWithImageFile("texture.png");

//Create a full size texture for example 1024,1024
CCTexture2D *texture = new CCTexture2D();
texture->initWithImage(image);

//Create a sprite from the require portion of texture (Here size of created sprite will be 300,300);
CCSprite *spriteNew = CCSprite::createWithTexture(texture, requiredPortion);

//Setting anchor point to make sure we are drawing from required position on screen
spriteNew->setAnchorPoint(ccp(0, 0));

//Set scale to sprite to make it fit in you required area i.e (requiredSize/currentSize)
spriteNew->setScale(drawArea.size.width/requiredPortion.size.width);
spriteNew->setPosition(drawArea.origin);

someNode->addChild(spriteNew);

make sure you delete image and texture later, they are not autorelease.