我正在尝试可视化一些数据,我需要交互性。我把我想要想象的实体表示为像太阳系一样移动的球。为了获得这一点,我使用了旋转和平移。但是,当我使用距离函数显示实体的名称时,它会出现故障并在其他地方显示名称,并且需要在其他地方进行交互,这与我的想法也不同。这是我的代码的一个非常简化的版本,带有注释。
//the angle (t) and theta factor as tt
var t=0;
var tt=0.01;
function setup()
{
//creating canvas to darw
createCanvas(600,600);
}
function draw()
{
background(255);
//translating the 0,0 point to the center of the canvas
translate(width/2,height/2);
//applying rotation on the matrix
rotate(1);
//gaining circular movement through sine and cosine oscillation
x=sin(t)*100;
y=cos(t)*50;
//drawing the ball
ellipse(x,y,10,10);
//when the mouse is inside the ball, a text is supposed to appear with the ball that says "on it"
if(dist(mouseX,mouseY,width/2+x,height/2+y)<5)
{
text("on it",x,y);
}
//incrementing the angle
t+=tt;
}
没有任何故障。您的问题是由以下事实引起的:mouseX
和mouseY
始终位于屏幕空间中,在进行平移和旋转后,坐标位于模型空间中。
您必须将鼠标坐标投影到模型空间中。不幸的是,P5.js没有处理所具有的modelX()
和modelY()
功能,因此您将不得不自己执行此操作。请参阅乔治对这个问题的回答,以获取有关如何做到这一点的出色指南。
我能想到的另一种选择是将所有绘图都绘制到一个P5.Renderer
而不进行旋转或平移,因此渲染空间和模型空间将是相同的。然后在绘制之前旋转整个事物。不确定这是否会完全按照您想要的方式工作,但值得研究。更多信息可以在参考中找到。