Question about Objects and Images

I've created a class which contains an image:

If I include the loadimage in the display function, it works:

class Hand {
  int x;
  int y;
  PImage thehand;
  Hand() {
   x=100;
   y=100;
  }
  void display(){
 thehand=loadImage("hand.png"); 
   image(thehand,x,y); 
  }
}

But that's wrong, since the loadimage keeps happening with each cycle through display (as opposed to once when the object is created.)

Putting: thehand=loadImage("hand.png") in

    Hand() {
           x=100;
           y=100;
           thehand=loadImage("hand.png")
          }

leads to an error that the image can't be found with the line: "image(thehand,x,y)" highlighted.

What am I missing?

Tagged:

Answers

  • edited October 2013 Answer ✓

    Loading images is a very slow process! 8-} Best place to do is within setup()! ;))
    This way, we only display() it within draw().

    Check it out how I've tweaked your class: (~~)

    Hand myHand;
    
    void setup() {
      size(500, 500);
    
      myHand = new Hand( loadImage("hand.png") );
    }
    
    void draw() {
      background(0);
    
      myHand.display();
    }
    
    class Hand {
      int x = 100, y = 100;
      final PImage theHand;
    
      Hand(PImage img) {
        theHand = img;
      }
    
      void display() {
        image(theHand, x, y);
      }
    }
    
  • This is great and it works. Thanks. Just wondering for future reference. Can you load the image within the object. I'm pretty sure I've seen examples that do this. Or is this just not how it works.

  • edited October 2013 Answer ✓

    Can you load the image within the object?

    You mean, within the class itself? If so, just put the loadImage() function inside the class' constructor! (*)

    Hand myHand;
    
    void setup() {
      size(500, 500);
    
      myHand = new Hand("hand.png");
    }
    
    void draw() {
      background(0);
    
      myHand.display();
    }
    
    class Hand {
      int x = 100, y = 100;
      final PImage theHand;
    
      Hand(String name) {
        theHand = loadImage(name);
      }
    
      void display() {
        image(theHand, x, y);
      }
    }
    
  • Got it. The key is that the file is called in the main program. Is that it?

    Also, what does "final" do in line 17. It does work without it.

  • edited October 2013

    Also, what does "final" do in line 17. It does work without it.

    For the program as a whole, that final there does nothing! :-\"
    It's just a remark for any1 trying to debug the code not to worry about variable theHand changing its stored value once set. :D

    The key is that the file is called in the main program.

    More specifically, before program reaches draw()! B/c that's by default invoked at 60 FPS! $-)

Sign In or Register to comment.