Why do images get stuck together on my cursor when I click and drag them?

edited October 2017 in Questions about Code

I am creating a dress up game. The setup is going to be base body on the left and organized clothes on the right. The user should click and drag the image to the body. There will be about 20-30 draggable items in total, so I want to make a function or class that can give all the images the same functionality rather than write the code 30 times.

I am not sure if my code is the most efficient way of doing that?

Also two problems currently:

  1. When I click on an image, and that image makes contact with another, they both get stuck to the cursor.

  2. The cursor feedback only works for the last image I draw, and is glitchy for the one before.

Here is my code so far (in the comments):

Tagged:

Answers

  • Img girl;
    Img bat;
    void setup(){
      size(1100,700);
      //Img(String tempFileName , int tempImgX, int tempImgY, int tempSizeX, int tempSizeY)
      girl = new Img("girl.gif", 300, 400 , 100, 100);
      bat = new Img("demonwing.png", 700,100, 200, 200);
    }
    void draw(){
      background(255,163,96);
    girl.move();
    bat.move();
    girl.display();
    bat.display();
    }
    
    //All movable objects on the screen
    class Img{
      PImage img;
      String fileName;
      int imgX; //center coordinates of image
      int imgY; 
      int sizeX;//sizing of image, maybe all the same?hopefully
      int sizeY;
    Img(String tempFileName , int tempImgX, int tempImgY, int tempSizeX, int tempSizeY){
      fileName = tempFileName;
      imgX = tempImgX;
      imgY = tempImgY;
      sizeX= tempSizeX;
      sizeY= tempSizeY;
      img = loadImage(fileName); //image is referred to as img
    }
    void display(){
      imageMode(CENTER);
      image(img, imgX, imgY, sizeX, sizeY);
    }
    void move(){ 
      if (mouseX> imgX - img.width/2 && mouseX< imgX + img.width/2
         && mouseY > imgY-img.height/2 && mouseY< imgY+img.height/2){
           cursor(HAND);
           if (mousePressed){
             cursor(CROSS);
             imgX= mouseX;
             imgY= mouseY;
           }} else{
             cursor(ARROW);
           }        
    }}
    
    
  • I think the problem is that more than one thing will match your mouse coords and the way the code is currently it'll move all the selected shapes.

  • Read the Common Question about arrays our classes. You'll need when you have 30 images.

    It also has the benefit that when you're iterating over the array you can break when you get a match, meaning only the topmost item will move with the mouse.

This discussion has been closed.