Javascript 如何使对象在给定时间内在p5.js中移动?
假设我有一张1200像素的画布。如何使对象在给定时间(例如10秒)内从起点(100px)移动到终点(1000px)?这样,对象从起点到终点只需10秒 到目前为止,我的代码如下所示:Javascript 如何使对象在给定时间内在p5.js中移动?,javascript,p5.js,Javascript,P5.js,假设我有一张1200像素的画布。如何使对象在给定时间(例如10秒)内从起点(100px)移动到终点(1000px)?这样,对象从起点到终点只需10秒 到目前为止,我的代码如下所示: function setup() { createCanvas(img.width, img.height); //Initialize x with the start value x = startX; } function draw() { image(img, 0,
function setup()
{
createCanvas(img.width, img.height);
//Initialize x with the start value
x = startX;
}
function draw()
{
image(img, 0, 0);
x = min(endX, x);
x+=2;
//stop the object if it's near enough to endx and endy
if (abs(endX - x) < 30)
{
x = endX;
}
y = 114;
//stop the object if it goes off of the screen
x = min(x, 1200);
x = max(x, 0);
var spotlightSize = 114;
blendMode(BLEND);
background(10);
image(spotlight_image, x-spotlightSize/2, y-spotlightSize/2, spotlightSize, spotlightSize);
blendMode(DARKEST);
image(img, 0, 0);
}
函数设置()
{
createCanvas(img.width,img.height);
//用起始值初始化x
x=startX;
}
函数绘图()
{
图像(img,0,0);
x=最小值(endX,x);
x+=2;
//如果对象足够接近endx和endy,请停止该对象
如果(abs(endX-x)<30)
{
x=endX;
}
y=114;
//如果对象离开屏幕,请停止该对象
x=最小值(x,1200);
x=最大值(x,0);
var spotlightSize=114;
blendMode(BLEND);
背景(10);
图像(聚光灯图像,x-spotlightSize/2,y-spotlightSize/2,spotlightSize,spotlightSize);
混合模式(最暗);
图像(img,0,0);
}
如果帧速率是完美且恒定的,您只需将移动距离除以所需时间内的帧数即可。结果就是你需要在每一帧中走多远。帧速率不是完美的或恒定的,但我们将编写一个假设完美帧速率的程序,因为它将在以后帮助我们
您需要做的是:
新p5();
常数fps=60;//每秒帧数
const startPos=createVector(100,50);
var position=startPos.copy();
const endPos=createVector(600450);
常数stopAtDist=30;//如果在任何方向都离终点这么远,就停下来
常量distToTravel=p5.Vector.sub(endPos,startPos);
常量移动持续时间=10;//移动持续时间(秒)
常量moveDurationFrames=moveDurationS/(1/fps);//移动距离需要多少帧
const distToMovePerFrame=p5.Vector.div(distToTravel,moveDurationFrames);//每帧移动多远
var currentlyMoving=真;
函数设置(){
createCanvas(800500);
帧速率(fps);
}
函数绘图(){
背景(0);
//绘制起始位置
笔划(‘黄色’);
冲程重量(10);
点(startPos.x、startPos.y);
//画出末端位置
笔划(‘绿色’);
点(末端位置x,末端位置y);
//绘制当前位置
笔划(‘红色’);
点(位置x,位置y);
//如果当前正在移动,则移动
如果(当前正在移动){
位置。添加(distToMovePerFrame);
}
//如果距离终点足够近,则停止
如果(abs(距离(位置x,位置y,末端位置x,末端位置y))
不过,帧速率不是恒定的。幸运的是,p5有一个函数告诉我们在最后一帧中经过了多少毫秒。因此,我们要做的是:
新p5();
常数fps=60;//每秒帧数
const startPos=createVector(100,50);
var position=startPos.copy();
const endPos=createVector(600450);
常数stopAtDist=30;//如果在任何方向都离终点这么远,就停下来
常量distToTravel=p5.Vector.sub(endPos,startPos);
持续时间=10;
const moveDurationMs=moveDurationS*1000;
const distToMovePerMs=p5.Vector.div(distToTravel,moveDurationMs);
var currentlyMoving=真;
函数设置(){
createCanvas(800500);
帧速率(fps);
}
函数绘图(){
背景(0);
//绘制起始位置
笔划(‘黄色’);
冲程重量(10);
点(startPos.x、startPos.y);
//画出末端位置
笔划(‘绿色’);
点(末端位置x,末端位置y);
//绘制当前位置
笔划(‘红色’);
点(位置x,位置y);
//如果当前正在移动,则移动
如果(当前正在移动){
var thisFrameMovement=p5.Vector.mult(distToMovePerMs,deltaTime);
位置。添加(此框架移动);
}
//如果距离终点足够近,则停止
如果(abs(距离(位置x,位置y,末端位置x,末端位置y))
我测试了上面的代码,结果非常准确——平均降价0.75%。我希望这就是你在你的答案中寻找的