在处理 (2) 中,我当前正在以类似 UML 的风格创建 Java 类图。类、接口(interface)等表示为矩形,使用处理的 rect()
方法创建。为每个要显示的矩形创建一个类,存储有关它的信息,并使用绘制矩形的 display()
方法。
为了实现该图的放大和缩小(以方便非常大或非常小的项目),我添加了代码,每次鼠标滚轮滚动时都会更改 scale
变量。然后,每次绘制类矩形等时,代码都会使用处理的 scale()
方法。
我还尝试检测何时将鼠标悬停在这些矩形之一上。目前,这是通过在表示矩形的类中使用以下代码来完成的:
//Checks to see if a mouse X and Y (posX and posY) position is inside the rectangle.
public boolean positionCollides(int posX, int posY) {
boolean xCollides = false, yCollides = false;
if((centreX + (width/2) >= posX) && (centreX - (width/2) <= posX)){
xCollides = true;
}
if((centreY + (height/2) >= posY) && (centreY - (height/2) <= posY)){
yCollides = true;
}
if(xCollides && yCollides){
return true;
}
else{
return false;
}
}
其中 mouseX
和 mouseY
被输入到该方法中。请注意,在此代码中,centreX
和 centreY
是变量,其中包含首次创建矩形时的矩形中心坐标。
但是,当我放大并将缩放应用于矩形的 display()
方法时,鼠标悬停会中断 - 大概是因为这些内容显示在稍微不同的 X 和 Y 坐标上,并且它仍在检查旧的。
有没有办法可以更改上面的 positionCollides
方法来帮助它处理缩放结果?我怎样才能解决这个问题?
我尝试通过在显示方法中的 scale()
调用之后放置调用 positionCollides
的代码来对此进行排序(试图获取 mouseX 和mouseY 值也要缩放),并将 mouseX 和 mouseY 乘以缩放比例(即 0.9、1.1)来尝试将它们获取到正确的值。
也许有一种方法可以动态改变对象的 centerX 和 centerY ?
感谢您阅读我的文字墙。
tl;dr - 如何检测鼠标指针是否位于已在处理中缩放的形状/矩形内?
最佳答案
在这里,试试这个:
(在处理1.5中测试)
int x, y, sz;
float factor = 0.87;//any value here
float transx = 50;//any value here
float transy = 25;//any value here
void setup()
{
size(400, 400);
x=100;
y=100;
sz=50;
}
void draw()
{
noFill();
//draw at original positon, no fill
rect(x, y, sz, sz);
scale(factor);
translate(transx, transy);
fill(255);
//draw after scalling and positioning filled this is tested for insidness
rect(x, y, sz, sz);
if ( mouseX / factor - transx > x &&
mouseX / factor - transx < x+sz &&
mouseY / factor - transy > y &&
mouseY / factor - transy < y+sz)
{
println("i'm inside!!!");
}
else
{
println("i'm outside");
}
}
关于java - 如何在处理中查找缩放形状上的距离/检测鼠标悬停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13343444/