Obtaining mouse coordinates in current coordinate system

大憨熊 提交于 2019-12-13 06:14:44

问题


How may I obtain the mouse coordinates in the current coordinate system i.e. in the coordinate system determined by the transformation matrix?

mouseX and mouseY return coordinates in untransformed screen space.


回答1:


One option is to keep track of the transformation matrix manually and use the inverse transformation to convert between local and global coordinate systems.

To convert from the global to the local coordinate system, multiply the global position to the inverse of the local coordinate system. Here's a very basic example:

//local coordinate system
PMatrix2D coordinateSystem;
//ineverse local coordinate system
PMatrix2D inverseCoordinateSystem;

PVector global = new PVector();
PVector local = new PVector();

void setup(){
  size(400,400);

  coordinateSystem = new PMatrix2D();
  //move to centre
  coordinateSystem.translate(width * .5, height * .5);
  //rotate 45 degrees
  coordinateSystem.rotate(HALF_PI * .5);

  //inverse coordinate system - clone the regular one, then simply invert it
  inverseCoordinateSystem = coordinateSystem.get(); 
  inverseCoordinateSystem.invert();

  fill(128);
}

void draw(){
  background(255);

  pushMatrix();
  applyMatrix(coordinateSystem);
  rect(0,0,100,100);
  popMatrix();

  //set global coordinates
  global.set(mouseX,mouseY);
  //compute local coordinates by multiplying the global coordinates to the inverse local coordinate system (transformation matrix)
  inverseCoordinateSystem.mult(global,local);

  text("global coordinates:" + global+
      "\nlocal coordinates:" + local,15,10);
}

Notice that the local coordinates are 0,0 when the cursor is at the top of the diamond.

The same principle applies in 3D, just need to use a PMatrix3D instead




回答2:


Questions like this are best answered by perusing the Processing reference. Specifically, the modelX() and modelY() functions do exactly what you want: they convert from screen coordinates to transformed coordinates.



来源:https://stackoverflow.com/questions/42867072/obtaining-mouse-coordinates-in-current-coordinate-system

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!