获取当前坐标系中的鼠标坐标 [英] Obtaining mouse coordinates in current coordinate system

查看:84
本文介绍了获取当前坐标系中的鼠标坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取当前坐标系中的鼠标坐标,即由变换矩阵确定的坐标系?

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

mouseX 和 mouseY 返回未转换屏幕空间中的坐标.

mouseX and mouseY return coordinates in untransformed screen space.

推荐答案

一种选择是手动跟踪变换矩阵,并使用逆变换在局部坐标系和全局坐标系之间进行转换.

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);
}

请注意,当光标位于菱形顶部时,本地坐标为 0,0.

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

同样的原理适用于 3D,只需要使用一个 PMatrix3D 代替

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

这篇关于获取当前坐标系中的鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆