Given I have a field with several rectangles like shown in the picture. A point with its x and y coordinates are given. The height(h) and the width(w) are also given. How can I calculate the top left corner with x, y h and w?


closed as off-topic by m_goldberg, MarcoB, user9660, Öskå, kjo May 28 '16 at 17:45

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question cannot be answered without additional information. Questions on problems in code must describe the specific problem and include valid code to reproduce it. Any data used for programming examples should be embedded in the question or code to generate the (fake) data must be included." – m_goldberg, MarcoB, Community, Öskå
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    $\begingroup$ pos + size/2 ? $\endgroup$ – Kuba May 27 '16 at 13:35
  • $\begingroup$ hm doesn't work for my example $\endgroup$ – Kris May 27 '16 at 13:40
  • $\begingroup$ So your origin is the upper left hand corner? $\endgroup$ – gwr May 27 '16 at 13:44
  • $\begingroup$ Correct. The purpose is a 2d Game where the user clicks somewhere into the field and the program needs to put a thing to the top left corner of a square in a field of squares $\endgroup$ – Kris May 27 '16 at 13:47
  • $\begingroup$ I'm voting to close this question as off-topic because this question is about middle-school level math; nothing to do with Mathematica. $\endgroup$ – kjo May 28 '16 at 17:45

The solution is to work in grid positions, e.g. gridX × height and gridY × width to come up with screen coordinates that have to be corrected by an offset to line up the grid-origin one is using with its true screen coordinates.

The position in the grid can be obtained by using Quotient thus returning the grid coordinates as integers.

In the given example the width of a box (assuming the red point is in the middle) is 200 and the height is 120 so the x-Axis confusingly here is the ordinate and the x-Axis the abscissa:

Clear[ leftCorner ];
leftCorner[ x_, y_, w_, h_ ] := With[
      offset = {50, 80} (* needed to correct for true screen position *)

  { Quotient[ x, h ], Quotient[  y, w ] } × {h, w} + offset


leftCorner[ 230, 180, (* w = *) 2 (180 - 80), (* h= *) 2 (230-170)  ]


leftCorner[ 100, 100, 200, 120]


So the origin of our implicit grid for calculations would be the left corner of the box above the marked one in the OP.

  • $\begingroup$ I have now changed w and h to match the OP exactly where the axis are confusingly given with x-Axis as ordinate and y-Axis as abscissa. This all of course had to be deduced from a somewhat sloppy graph... $\endgroup$ – gwr May 28 '16 at 8:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.