在p5.js中跟踪鼠标位置

时间:2018-04-29 23:07:01

标签: p5.js

作为我项目的一部分,我必须根据我绘制的椭圆是朝向还是远离鼠标来打印某个短语:

" 4-更新beast.message,说明它是在追逐还是逃离鼠标 创建并使用名为movingTowardsMouse的布尔变量 如果movingTowardsMouse为true,则该消息应该说“追逐鼠标”。 如果movingTowardsMouse为false,则该消息应该说“逃离鼠标”'"

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

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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

相关问题