After mouse click image disappears and shows up in new random position

edited November 2017 in Questions about Code

I need help with my code in processing. It is actually a short and easy code, but I am a beginner in programming, so for me seems everything difficult... :(

My goal is...

To click on an image. After the mouse click, the image should disappear and show up in a new random position. Then I should be able to click on the image in the new random position, and it should do the same again: disappear and show up in a new random position. and so on. I have written some code (see below), but it does not work properly. I would really appreciate it if someone could help me to find out, what is wrong with my code. Thank you very much in advance! :)

Here is my code:

PImage pic;

// Declare variables for the picture float pic_x; float pic_y; float pic_r = 100;

float pic_x_new = random(0, 400); float pic_y_new = random(0, 400);

boolean mouseOverPic;

void setup(){ size(500,500); background(0,100,0);

//loading the picture pic = loadImage("pic.png"); image(pic, pic_x, pic_y, pic_r, pic_r); }

void draw(){

mouseOverPic = mouseX <= pic.width && mouseX >= pic_x && mouseY <= pic.height && mouseY >= pic_y;

if (mousePressed && mouseOverPic) { background(100); image(pic, pic_x_new, pic_y_new, pic_r, pic_r);
}
}

Tagged:

Answers

  • Look into using the mousePressed() function - not the mousePressed boolean. The mousePressed() function will run once when the mouse is pressed. This is good, because you only need to do things once per mouse click, not once per each frame that the mouse is held down.

    When the mouse is pressed, you will first need to check to see if it was pressed on the image. If it wasn't, great. Then there's nothing to do. If it was, then you will need to move the image to a new position. But you don't need to draw it in a different position - just change the values stored in the variables that you are using when you draw the image.

  • Also: please edit your post (gear icon) and format (highlight code, Ctrl-o to indent four spaces, code separated by a blank line)

    https://forum.processing.org/two/discussion/15473/readme-how-to-format-code-and-text

  • You can use the next code, I already prove it:

      PImage pic;
      int value = 0;
      float x, y = 0; //In this constants I will save the random value of the positions
    
      void setup(){ 
    
      size(500,500); 
      //loading the picture 
      pic = loadImage("pet.jpeg"); 
      background(0,100,0);
    
      }
    
      void draw(){
    
      image(pic, x,y, 100,100); //You can check the reference of image
    
      }
    
      void mouseClicked(){
    
      x = random(500);
      y = random(500);
      redraw();  //This functions allows the program to update the display window
    
      }
    

    Screen Shot 2017-11-20 at 1.00.58 Screen Shot 2017-11-20 at 1.01.09

    I upload the program here:

Sign In or Register to comment.