获取当前坐标系下的鼠标坐标
Obtaining mouse coordinates in current coordinate system
如何获取当前坐标系即变换矩阵确定的坐标系中的鼠标坐标?
mouseX 和 mouseY return 未转换屏幕中的坐标 space。
一种选择是手动跟踪变换矩阵并使用逆变换在局部坐标系和全局坐标系之间进行转换。
要从全局坐标系转换为局部坐标系,请将全局位置乘以局部坐标系的倒数。这是一个非常基本的例子:
//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);
}
注意,当光标位于菱形的顶部时,局部坐标为 0,0。
同样的原理也适用于 3D,只需要使用 PMatrix3D 代替
像这样的问题最好通过仔细阅读 the Processing reference 来回答。具体来说,modelX()
和 modelY()
函数完全符合您的要求:它们将屏幕坐标转换为转换后的坐标。
如何获取当前坐标系即变换矩阵确定的坐标系中的鼠标坐标?
mouseX 和 mouseY return 未转换屏幕中的坐标 space。
一种选择是手动跟踪变换矩阵并使用逆变换在局部坐标系和全局坐标系之间进行转换。
要从全局坐标系转换为局部坐标系,请将全局位置乘以局部坐标系的倒数。这是一个非常基本的例子:
//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);
}
注意,当光标位于菱形的顶部时,局部坐标为 0,0。
同样的原理也适用于 3D,只需要使用 PMatrix3D 代替
像这样的问题最好通过仔细阅读 the Processing reference 来回答。具体来说,modelX()
和 modelY()
函数完全符合您的要求:它们将屏幕坐标转换为转换后的坐标。