我是JavaScript的新手,想制作一个简单的脚本,其中一个对象(在这种情况下是一个正方形)向光标移动。这个想法是方形跟踪光标,随着它越来越慢而减速。到目前为止,我的代码看起来像这样:
var xspeed;
var yspeed;
var x;
var y;
function setup() {
createCanvas(500,500);
}
function update(){
xspeed = (mouseX - x)/2;
yspeed = (mouseY - y)/2;
x += xspeed;
y += yspeed;
}
function draw() {
background(255);
x = width/2;
y = height/2;
while (!(x == mouseX && y == mouseY)){
update();
rect(x,y,10,10);
}
}
问题是,这段代码只会弹出一堆静态的正方形,并放在从中心到左上角的对角线上。似乎代码完全忽略了光标的位置。
我做错了什么?提前谢谢!
答案 0 :(得分:0)
while
函数中有一个draw()
循环,这意味着在while
循环结束之前第一帧不会完成。 while
循环直到方块直接位于鼠标顶部,默认情况下为0,0。
摆脱while
循环。当你在它的时候,你不想检查方块是否直接在鼠标顶部,因为它可能只会非常接近鼠标。检查完全匹配将导致代码进入无限循环,这将使浏览器崩溃。
答案 1 :(得分:0)
您需要的是计算指向鼠标的向量,并使用它来修改矩形x和y
在p5.js中,向量是一个存储可以修改的x,y和z值的对象,
你想要的是你的绘制循环做这样的事情:
var rectLocation;
function setup() {
// create vector that keeps track of the location of the rect
rectLocation = createVector(width/2,height/2);
}
function draw() {
// Assign your mouseX and mouseY to a vector called target.
var target = createVector(mouseX,mouseY);
// Calculate the distance between your target and
// the current location of your rect
var distance = target.dist(rectLocation);
// map the distance between your rect location and
// the mouse to a new number which will dictate how
// much slower it will move based on how close it
// will get to the target.
var mappedDistance = map(distance, 100, 0, 1.5, 0.5);
// this is where you actually calculate the direction
// of your target towards your rect.
target.sub(rectLocation);
// then you're going to normalize that value
// (normalize sets the length of the vector to 1)
target.normalize();
// then you can multiply that vector by the distance
// we mapped to a new number (in this case it gets
// multiplied somewhere between 1.5 and 0.5 based
// on how far the target is.)
target.mult(mappedDistance);
// last we add the target vector (which we modfied
// multiple times) to the rect location.
rectLocation.add(target);
// draw and watch math do it's job!
rect(rectLocation.x, rectLocation.y, 10,10);
}
我建议在youtube上查看daniel shiffman制作的教程。他非常详细地解释了一切。