best way to group images for mouse press function

edited October 2015 in How To...

Hi, I'm reaallllly new to Processing and I'm trying to create a drag and drop dress-up game.

What's the best way to go about grouping upload images together so I can apply a mousePressed and mouseReleased function too all of them at the same time? So each image can be dragged and dropped.

Answers

  • You need to create a class that will have the needed functionality. Your image would be a part of the class. Something like this, but can be improved:

        boolean isDrag;
        boolean clicked;
        DraggableImage myImage;
    
        void setup() {
            size(500, 500);
            myImage = new DraggableImage("yourImage.png", 0, 0);
        }
    
        void draw() {
            background(255);
            myImage.display();
        }
    
        void mousePressed() {
            isDrag = true;
            clicked = true;
        }
    
        void mouseReleased() {
            isDrag = false;
            clicked = false;
        }
    
        class DraggableImage {
            PImage img;
            float x;
            float y;
            float offsetX, offsetY;
            DraggableImage(String src, float x_, float y_) {
                img = loadImage(src);
                x = x_;
                y = y_;
            }
            void display() {
                getOffset();
                if (isDrag) {
                    if (mouseX > x && mouseX < x + img.width && mouseY > y && mouseY < y + img.height) {
                        x = mouseX - offsetX;
                        y = mouseY - offsetY;
                    }
                }
                image(img, x, y);
            }
            void getOffset() {
                if (clicked) {
                    offsetX = mouseX - x;
                    offsetY = mouseY - y;
                    clicked = false;
                }
            }
        }
    

    For storing multiple objects, read about arrays.

Sign In or Register to comment.