在 p5.js 中跟踪鼠标位置

Track mouse position in p5.js

作为我项目的一部分,我必须打印一个特定的短语,这取决于我绘制的椭圆是朝向还是远离鼠标移动:

"4-更新beast.message说是追还是逃鼠标 创建并使用一个名为 movingTowardsMouse 的布尔变量 如果 movingTowardsMouse 为真,则消息应显示 'Chasing mouse' 如果 movingTowardsMouse 为 false,消息应为 'Fleeing mouse'"

我想知道对我来说最简单的方法是跟踪鼠标的位置以完成此任务。我已经尝试了几件事,但无济于事。 Google 也没能给我答案。任何帮助将不胜感激。这是我到目前为止的代码,为了清楚起见,我没有尝试任何解决方案。

var beast;
var color1;
var color2;
var color3;
var movingTowardsMouse = false;
var mousePosition;
var smallPoint;

function setup () {
  createCanvas(600, 200);

var cStrength1 = random(100, 255);
var cStrength2 = random(100, 255);
var tStrength = 150;
color1 = color(cStrength1, 50, cStrength2, tStrength);
color2 = color(cStrength2, cStrength1, 50, tStrength);
color3 = color(50, cStrength2, cStrength1, tStrength);

beast = {
  x: 0,
  y: height/2,
  size: 50,
speed: 4,
color: color(255),
message: "Chasing mouse",
}
smallPoint = {
  mousePosition: mouseX,
  y: mouseY,


}

}

function draw () {
  background(255);

var oneThird = width/3;
stroke(255, 255, 255, 50);
fill(color3);
rect(0, 0, width, height);
fill(color2);
rect(0,0, oneThird * 2,height);
fill(color1);
rect(0,0, oneThird,height);

if (beast.x >0 && beast.x < oneThird) {
  beast.color = color1;
} else if (beast.x > oneThird && beast.x < oneThird*2) {
  beast.color = color2;
} else if (beast.x >oneThird*2 && beast.x < width) {
  beast.color = color3;
}


fill(beast.color);
ellipse(beast.x, beast.y, beast.size, beast.size);


if (beast.x > width) {
  beast.speed= -beast.speed;
} else if(beast.x <= 0) {
  beast.speed= 4;
}
 point(smallPoint.mousePosition, smallPoint.Y);

beast.x = beast.x + beast.speed;




fill(255);
 text(beast.message, 10, 20);

请注意,您的作业中没有任何内容(至少您发布的部分)说您应该实际检测椭圆是移向还是远离鼠标。按照我的阅读方式,您现在应该只创建一个布尔变量并使用 truefalse 对其进行硬编码。我猜你稍后会添加更复杂的逻辑。

但要回答您的问题,您不需要跟踪鼠标来确定圆圈是否正在向鼠标移动。你只需要普通的旧 mouseXmouseY 变量。

但是,您需要跟踪圆圈的移动并将其与光标位置进行比较。您可以跟踪圆圈的先前位置和圆圈的当前位置。看看哪个离光标更近,它会告诉你圆圈是朝着光标移动还是远离光标。

但是,我的猜测是您实际上不应该这样做。我的猜测是,您最终会编写一些代码,根据它是否在追逐光标来移动圆圈。变量决定运动,而不是运动决定变量。