Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: About switching between images  (Read 1633 times)

0 Members and 1 Guest are viewing this topic.

fabvman

  • Newbie
  • *
  • Posts: 11
    • View Profile
About switching between images
« on: February 27, 2011, 10:56:34 pm »
What if I have two images loaded in different sf::image objects and you want to display one image or another depending of the situation?
I mean, I have a class named character and I need a method to change the image to display. I was trying something like this:

( in main() )

Code: [Select]
sf::image *img1 = new sf::image();
sf::image *img2 = new sf::image();
img1->loadfromfile("img1.png");
img2->loadfromfile("img2.png");
sprite->setimage(*img1);
Character *character = new Character(*img1);
/* in the class I do  image = img1, where "image" is sf::image *image; */


and later in the game I need to change the sf::image of the character, then I do something like
Code: [Select]
character->setimage(*img2);
/* in the class i tried this:
delete image;
image = img2;
sprite->setimage(*image);*/


and trows and exception.
What is wrong? How can I do that in the right way?
Thanks.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
About switching between images
« Reply #1 on: February 27, 2011, 11:52:33 pm »
Why is everyone using pointers for no reason?
Your code can be simplified:
Code: [Select]
sf::Image img1;
sf::Image img2;
if (!img1.loadfromfile("img1.png") || !img2.loadfromfile("img2.png"))
    HandleErrors();

sf::Sprite sprite(img1);
Character character(img1);

In this example, you don't have to use new and delete at all. Generally, these operators are unnecessary in many situations. Avoid manual memory management wherever possible. Like this, your code will be cleaner and have far less errors. It's likely that your problem disappears in this way.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: