gpt4 book ai didi

javascript - 使对象向光标移动 - JavaScript - p5.js

转载 作者:行者123 更新时间:2023-11-30 14:50:14 26 4
gpt4 key购买 nike

我是 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);
}
}

问题是,这段代码只会弹出一堆静态的方 block ,这些方 block 位于从中心到左上角的对 Angular 线上。看起来代码完全忽略了光标的位置。

我做错了什么?提前致谢!

最佳答案

你需要计算一个指向你鼠标的向量并用它来修改你的矩形 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 制作的教程。他非常详细地解释了一切。

关于javascript - 使对象向光标移动 - JavaScript - p5.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48250639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com