i'm facing problem with swapping transform(position, scale, rotate) of two object of same type that has transformable member data. i can do it by swapping each of them manually but i think this is noneffective. if i understood it correctly, i think this can be done by std::swap or by "=operator" which is used copy constructor of each given objects and their transform to the new object.
here example that supposed to work but it didn't.
#include <SFML/Graphics.hpp>
class Tile : public sf::Drawable
{
public:
Tile(const sf::Texture& texture)
: mSprite(texture)
, mTransform()
{
}
~Tile() = default;
Tile(const Tile& othher)
: mSprite(othher.mSprite)
, mTransform(othher.mTransform)
{
}
Tile& operator=(Tile other) noexcept
{
other.swap(*this);
return *this;
}
//Tile(Tile&& other)
//{
// swap(*this, other);
//}
//Tile& operator=(Tile&&) = default;
void swap(Tile& other) noexcept
{
using std::swap;
swap(mTransform, other.mTransform);
swap(mSprite, other.mSprite);
}
friend void swap(Tile& lhs, Tile& rhs) noexcept
{
using std::swap;
swap(lhs.mTransform, rhs.mTransform);
swap(lhs.mSprite, rhs.mSprite);
}
void setPosition(float x, float y)
{
mTransform.setPosition(x, y);
}
void setPosition(sf::Vector2f pos)
{
mTransform.setPosition(pos);
}
sf::Vector2f getPosition() const
{
return mTransform.getPosition();
}
void draw(sf::RenderTarget& target, sf::RenderStates states) const
{
states.transform = mTransform.getTransform();
target.draw(mSprite, states);
}
private:
sf::Sprite mSprite;
sf::Transformable mTransform;
};
int main()
{
sf::RenderWindow window(sf::VideoMode(480u, 480u), "Tile tut");
window.setVerticalSyncEnabled(true);
sf::Texture texture1, texture2;
if (!texture1.loadFromFile("0.png"))
return 1;
if (!texture2.loadFromFile("1.png"))
return 1;
Tile tile1(texture1), tile2(texture2);
tile1.setPosition(100.f, 120.f);
tile2.setPosition(100.f + texture1.getSize().x, 120.f);
bool toggle = false;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else if (event.type == sf::Event::KeyPressed)
{
if (event.key.code == sf::Keyboard::Space)
{
toggle = !toggle;
}
}
}
if (toggle)
{
toggle = false;
// normal position swap works fine:~ do same thing for rotate and scale
//auto pos = tile1.getPosition();
//tile1.setPosition(tile2.getPosition());
//tile2.setPosition(pos);
// doesn't works
//auto tile = tile1;
//tile1 = tile2;
//tile2 = tile;
//tile1.swap(tile2); // doesn't works
//std::swap(tile1, tile2); // doesn't works
}
window.clear();
window.draw(tile1);
window.draw(tile2);
window.display();
}
}
how to fixed this it, did i miss something that i should take care of?
Editsorry it seems the problem with sf::sprite's texture not with tansform, i fixed it