Strange Behavior Triggered by image() Function

I think I’ve narrowed down the problem. If you do a println(storedImage.hashCode()) in getImage() method Object, then you’ll get a number which is (probably) based the memory address of the object. I did similar things in different parts of the program so as far as I could tell there’s no copying happening (which is to be expected) all the variables are references to the same spriteImage.

I then commented out some sections and came to the conclusion the only bug is in the displayObjects(). So I tried:

  PImage displayObjects(){
    //localCanvas.beginDraw();
    //localCanvas.clear();
    for(int i=0; i<contains.size();i++){
      //localCanvas.image(contains.get(i).getImage(0),0,20*i);
      image(contains.get(i).getImage(0),0,20*i);
    }
    //localCanvas.endDraw();
    return localCanvas;
  }

Which worked seeming to indicate that the problem is with the localCanvas PGraphics. Seems like the clear() or image()(when applied to PGraphics) method isn’t working properly and I can’t really figure out why. I spent awhile trying to figure it out, but this solution seemed to work even if it’s not the most efficient.

  PImage displayObjects(){
    localCanvas=createGraphics(180,30);
    localCanvas.beginDraw();
    for(int i=0; i<contains.size();i++){
      localCanvas.image(contains.get(i).getImage(0),0,20*i);
    }
    localCanvas.endDraw();
    return localCanvas;
  }

Might look into it more later and see if there’s something I’m missing. And you’re completely right that you would just copy the image in the constructor if you want each image to be independent.

Side note: I know this is an example and in your real program you would come up other names for classes but I would still avoid using Object as a name class in examples. Because Object the most general Class in Java and is used in inheritance. So when you use it in a method signature like void addObject(Object takingInObject){ Java will think you mean a java.lang.Object (and by inheritance every object) not specifically your Object. Which seemed to work out fine in this case but if you do this regularly you might get some weird implicit casting that might be hard to debug.

1 Like