Swapping two sprites

i have a class with a sprite property . trying to swap the sprite between two objects of the class using

std::swap(this->tileSprite, targetTile->tileSprite);
or
the standard swap technique of assigning to a temporary variable and so on…

but i’m not able to get the desired result … is it possible to do this???

You should use the methods Sprite::getTexture and Sprite::setTexture.

tried it… not happening … exactly what i want is to swap two class objects … the sprite property of one object to point to another objects sprite… i hope i making it clear… thanks fradow for quick reply

std::swap is just a template for swapping with a temporary. The types have to be the same.

What is the result you are getting?
Swapping sprite pointers work perfectly this way.

trying to do this, obj[0]'s sprite must contain obj[1]'s sprite , tried that std::swap template , not working … to verify tried printing out the addresses …

So you have tried something like
Sprite* temp = obj[0]->sprite;
obj[0]->sprite = obj[1]->sprite;
obj[1]->sprite = temp;

and afterwards what doesn’t happen?

Remember this only swaps the references from the obj - noting will happen on screen (i.e. the location, size, rotation etc, of each sprite will be unchanged, unless your code does something to change that)

Only tried or really printed them out?

If you are applying the std::swap method(which is just doing the stuff @Maxxx was posting) to the pointers, the addresses will get swapped.

The template is implemented like this:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}

code snippet

targetTile = &tileList[row][col - 1]; //row = 0 and col = 1

swapping code :

CCLOG(" before swap target %d this %d" , (int)&(targetTile->tileSprite) , (int)&(this->tileSprite));
std::swap(this->tileSprite, targetTile->tileSprite);
CCLOG(" after swap target %d this %d" , (int)&(targetTile->tileSprite) , (int)&(this->tileSprite));

result :
cocos2d: before swap target 6452864 this 6453552
cocos2d: after swap target 6452864 this 6453552

Your CCLOG have a strange syntax, and I’m almost sure it’s wrong (displaying the address of the pointer, which is never going to change, not the address of what the pointer points to, which is the relevant value). The format to see which address a pointer points to is %p.

What is the result of this code ?

CCLOG(" before swap target %p  this %p" , targetTile->tileSprite , this->tileSprite));
std::swap(this->tileSprite, targetTile->tileSprite);
CCLOG(" after swap target %p  this %p" , targetTile->tileSprite , this->tileSprite));
1 Like

fradow thanks!!! i was printing it wrong … i still have to figure out the other and the actual mistake i’m making cos of which the values are not getting reflected on the swapped objects. I’ll keep you updatedif they dont close this post… :slight_smile: