Moving grid to position where mouse is clicked

Hi all,

I have been trying to solve this problem for hours. What I am aiming for is that I move the grid that is underlying the Processing screen to where my mouse is clicked, so that I can draw something from here that grows as I move the mouse.

Could you guys help me with this? Thank you so much!

Cheers~

Answers

  • Answer ✓
    float savedX, savedY;
    
    void setup(){
      size(440,440);
    }
    
    void draw(){
      background(0);
      if( mousePressed ){
        savedX = mouseX;
        savedY = mouseY;
      }
      translate(savedX, savedY);
      stroke(255,0,0);
      line(0,0,100,0);
      stroke(0,255,0);
      line(0,0,0,100);
    }
    
  • Ah allright! I did not understand that I had to define the starting point in savedX, savedY and not just use the mouseX, mouseY out of nowhere :P

  • The important thing to remember is that every frame, Processing updates the value of the mouseX / mouseY variables based on where the mouse is. You can use that information in combination with things you store yourself - like previous mouse values saved at a particular moment in time.

    Wanting to know the very last mouse values is so common that Processing has an additional variable pair built-in for it: pMouseX / pMouseY. These are useful for drawing connected lines.

  • edited January 2018

    Thanks! So it always save the mouse position where it is, regardless of how the underlying grid is modified?

  • edited January 2018 Answer ✓

    Right. If I understand your question correctly -- mouseX / mouseY coordinates are not affected by translate() -- mouseX = 0 is the left-hand edge of your screen, no matter how the screen space is translated, rotated, scaled etc.

    You can map that by passing variables to translate and using the same variables on mouseX. So if you translate(50,25), and you want to draw where you click, draw at point(mouseX-50, mouseY-25)

    In 3D, you can also get a mapping back from coordinates to mouse using screenX() / screenY().

  • Yes, this was exactly what I didn't understand, thanks!

Sign In or Register to comment.