使用javascript移动某些内容,并使其移动速度变慢

使用javascript移动某些内容,并使其移动速度变慢,javascript,setinterval,Javascript,Setinterval,我有作业,不能解决它。我们必须让一颗心通过鼠标在任意方向上移动。就像在现实世界中一样,它的移动速度应该会变慢 我试图通过设置间隔来实现这一点,但我不能减少间隔,因此它不会变慢。这是我的代码,也许有人能帮上忙: script.js index.html 谢谢你 如果您需要它随时间移动,请确实这样做。我不会为你做家庭作业,但我会给你提纲,这样你就可以知道如何编程: - determine how many milliseconds MS you want the thing to move for

我有作业,不能解决它。我们必须让一颗心通过鼠标在任意方向上移动。就像在现实世界中一样,它的移动速度应该会变慢

我试图通过设置间隔来实现这一点,但我不能减少间隔,因此它不会变慢。这是我的代码,也许有人能帮上忙:

script.js index.html
谢谢你

如果您需要它随时间移动,请确实这样做。我不会为你做家庭作业,但我会给你提纲,这样你就可以知道如何编程:

- determine how many milliseconds MS you want the thing to move for (universal)
- determine the starting speed to move in (universal)
on mouseover:
  - determine the current object position (x,y)
  - determine the speed and direction of travel (dx,dy) for the object
  - record the mouseover start time for this object
  call update.
具有as更新功能:

update:
  - determine the current acceleration A as: map "now" from (start,start+MS) to (1,0).
  - determine the object's new position (x + A*dx, y + A*dx)
  - update (x,y) to be these new values
  if (f > 0):
    schedule a next call to update some time in the future.

这是一种在你坐下来编写程序之前不要立即开始编程分析的方法——实际的代码,因为这样,你现在知道在实现它们之前代码的所有部分都应该做些什么,当某些部分不起作用时,你会更容易发现,因为你已经知道它应该如何工作。

你可以尝试在每一步调用setTimeout,而不是setInterval,增加延迟。考虑到move函数中的代码,还有更多问题:你的问题陈述没有提到移动时改变方向,你显然没有查Math.random做了什么,因为它会产生一个介于0和1之间的数字,所以你的if语句永远不会计算为真。@Mike'Pomax'Kamermans:谢谢,这完全正确。@Oriol你的意思是我应该把setInterval的内容放在一个内部setTimeout中,并在这个范围内增加延迟吗?谢谢Mike,这是一个很好的方法。我无法确定对象的当前位置。它表示无法读取null的属性“getBoundingClientRect”:迈克,你能再帮我一点忙吗?当然,这不是让别人帮我做作业,但我真的一点也不想再做了。你提到的要点完全有道理,但我无法在代码中得到它。如果你引用了错误,这意味着你在查询选择的对象实际存在之前调用了这段代码。确保等待DOM准备就绪。在这种情况下,将其移动到之前,以便在DOM完成后运行。
- determine how many milliseconds MS you want the thing to move for (universal)
- determine the starting speed to move in (universal)
on mouseover:
  - determine the current object position (x,y)
  - determine the speed and direction of travel (dx,dy) for the object
  - record the mouseover start time for this object
  call update.
update:
  - determine the current acceleration A as: map "now" from (start,start+MS) to (1,0).
  - determine the object's new position (x + A*dx, y + A*dx)
  - update (x,y) to be these new values
  if (f > 0):
    schedule a next call to update some time in the future.