使用设定的距离和时间减速到停止

  • 本文关键字:时间 距离 python-3.x
  • 更新时间 :
  • 英文 :


我不是一个伟大的数学人,但我自己用python解决这个问题。

我试图实现的是从位置 0 开始的一维点,移动到小于等于 720 的随机位置。如果该点行进到最大距离 720,则需要 0.5 秒。该点还需要在该时间和随机位置内减速到停止。

这就是我到目前为止所做的,但显然这是错误的。

fps = 60
maxx = 720
x = 0 
px = rnd(0, maxx)
t = fps * (px / maxx)
s = 2.0 * px / (t * (t - 1))
v = s * t
while v > 0:
x += v
v -= s
print (x)

如果 px = 360,则 x 的结果应该是 384.82758620689657,而它应该是 360。

谢谢你的帮助。

好的,您似乎对某种"移动动画"感兴趣,CSS中通常称为"缓动"。

我找到了一些具有多个缓动及其实现的示例,并创建了一些基本源代码,您可以在其中尝试使用X坐标输出:)

对我来说看起来很棒!玩:)

from random import randint

# check more easings at websites:
# https://gist.github.com/th0ma5w/9883420
# https://easings.net/en#easeOutQuad
def easeInQuad(t, b, c, d):
t /= d
return c * t * t + b

fps = 60
maxx = 720
px = randint(0, maxx)
t = fps * (px / maxx)
print('Going to x={}'.format(px))
points = []
for i in range(int(t) + 1):
points.append(str(round(easeInQuad(i, 0, px, t))))
# Just make sure we stop at teh destination fixel
if points[-1] != str(px):
points[-1] = str(px)
print('X coords per frame tick: {}'.format(", ".join(points)))

输出

Going to x=409
X coords per frame tick: 0, 0, 1, 3, 6, 9, 13, 17, 23, 29, 35, 43, 51, 60, 69, 79, 90, 102, 114, 127, 141, 155, 170, 186, 203, 220, 238, 257, 276, 296, 317, 338, 361, 383, 409

查看更多缓动类型(数学公式(及其 python 类似物,请访问

  • https://gist.github.com/th0ma5w/9883420
  • https://easings.net/en#easeOutQuad

示例与轻松出昆特

请求的解决方案 #2 :)

from random import randint

# check more easings at websites:
# https://gist.github.com/th0ma5w/9883420
# https://easings.net/en#easeOutQuad
def easeOutQuint(t, b, c, d):
t /= d
t -= 1
return c * (t * t * t * t * t + 1) + b

fps = 60
maxx = 720
px = randint(0, maxx)
t = fps * (px / maxx)
print('Going to x={}'.format(px))
points = []
for i in range(int(t) + 1):
points.append(str(round(easeOutQuint(i, 0, px, t))))
# Just make sure we stop at teh destination fixel
if points[-1] != str(px):
points[-1] = str(px)
print('X coords per frame tick: {}'.format(", ".join(points)))

输出

# > python test.py
Going to x=703
X coords per frame tick: 0, 58, 112, 162, 209, 253, 293, 331, 366, 398, 427, 454, 480, 502, 524, 543, 560, 576, 591, 604, 616, 627, 636, 645, 653, 659, 666, 671, 676, 680, 684, 687, 689, 692, 694, 696, 697, 698, 699, 700, 701, 701, 702, 702, 702, 703, 703, 703, 703, 703, 703, 703, 703, 703, 703, 703, 703, 703, 703

最新更新