Set texture position inside a sprite

What I would like to do is to clip an image programmatically inside a sprite. I figured out I can do it this way

a2->setTextureRect(Rect(0.0, 0.0, 50.0, 50.0));

and this will show upper left quarter of the image.

How can I show for instance lower right quarter?

I tried this

a2->setTextureRect(Rect(50.0, 50.0, 50.0, 50.0));

but it seems first two arguments are always ignored.

Anyone?

I’ll try to put the problem another way. I have a board divided into 64 fields (looks like a chessboard). Each field contains one element, which can explode and hit surrounding fields. I have an animation of the explosion, which covers 9 fields (3 x 3). When an element blows up in the corner or at the edge, I want to show the animation only inside the board and hide the part outside the board. I don’t want to crop textures manually, because I would have to prepare and store 9 separate sets of textures. I would like to crop or hide textures programmatically.

Is is possible? How would you do that?

Here is a simple example. Let’s say we want to show the woman in the middle instead of the whole sprite

sprite->setTextureRect(Rect(103.0f, 47.0f, 94.0f, 220.0f));

Remember two things:

  • (0, 0) is in the top left corner (it is a bit confusing because it is different from general cocos2d-x coordinate system)
  • Size is a vector, not coordinates

I tested your use case and didn’t have any problem at all:

I added the following code to HelloWorld::init() in a new clean project in cocos2d-x-3.7:

    auto test = Sprite::create();
    test->setTexture(FILE_NAME);
    test->setTextureRect(Rect(LEFT, TOP, WIDTH, HEIGHT));
    addChild(test);

Everything worked fine.
When I changed LEFT or TOP, the displayed part of the texture changed accordingly… So I guess, the problem you’re facing must be somewhere else…
Sorry, if I’m not of much help here…
Just test it, create a new project, add the above code and look for yourself whether it is working…

Sorry, I forgot to mention I manage to solve the problem and it is a working solution. I just wanted to post the solution for others. It seems my problem was finding right parameters.