Search code examples
positionprocessing

Explaining coordinate's calculation with map()


Could someone explain the meaning of this value/position: 300-400/2+10. I know it makes that the red circle won't go out of the square but I don't really understand the calculation..? Is there a page where I can read how it works because I personally would do it like this

float  redCircle = map(mouseX,0,width,116,485);
circle(redCircle,map(mouseY,0,height,114,485),20);

with one number positions and not a calculation like in the code. I tried to understand it but I don't. I would really appreciate it if someone could explain the proceed.

    void setup() {
        size(600, 600);
      surface.setTitle("Mapping");
      surface.setLocation(CENTER, CENTER);
    }
    
    void draw() {
      background(0);
      stroke(255);
    
      fill(255, 255, 255);//weißer Kreis
      circle(mouseX, mouseY, 20);
      mouseMoved();
      text("Maus X/Y:"+mouseX+"/"+mouseY, 250, 300); //Text für weiße Position
    
     
      fill(255, 0, 0); //Roter Kreis
      float posFromMouseX = map(mouseX, 0, width, 300-400/2+10, 300-400/2+400-10);
      float posFromMouseY = map(mouseY, 0, height, 300-400/2+10, 300-400/2+400-10);
      ellipse(posFromMouseX, posFromMouseY, 20, 20);
      text("map to: "+posFromMouseX+" / "+posFromMouseY, 255, 320); //Text für rote Position
      
      // Transparentes Rechteck in der Mitte
      noFill();
      rect(300-400/2, 300-400/2, 400, 400); 
    }

Solution

  • map() will adjust the scale of a number accordingly to a range.

    For an example, if you have these values:

    MouseX: 200
    width: 1000
    

    You can easily calculate that, if the screen had a width of 2000 your mouse X position would need to be 400 to be proportional.

    But this is an easy example. In the code you pasted here, the same thing is happening, but the coordinates compared are:

    1. The whole window
    2. The white rectangle

    The map() function takes 5 args:

    map(value, start1, stop1, start2, stop2)
    
    1. value: float: the incoming value to be converted
    2. start1: float: lower bound of the value's current range
    3. stop1: float: upper bound of the value's current range
    4. start2: float: lower bound of the value's target range
    5. stop2: float: upper bound of the value's target range

    So... you can totally write this line without the calculations:

    float posFromMouseX = map(mouseX, 0, width, 110, 300-400/2+400-10);
    // is the same thing than:
    float posFromMouseX = map(mouseX, 0, width, 110, 490);
    

    The probables reasons to write it that way are:

    1. The author may not have wanted to do the simple math
    2. The author may want to know where these numbers come from later (seeing how they were calculated would help on this front)
    3. The author may want to change the hardcoded numbers for variables and make his white rectangle's size dynamic later

    Hope it makes sense to you. Have fun!