2

我有一个数学问题:

我有一个函数,其中唯一的参数是当前时间。返回应该是用于将对象放置在某个位置的位置。

int position(int time)
{
    int x = 0; //TODO implement x depending on time
    return x;
}

所以基本上每帧都会调用该函数以使对象运动。

动议应如下所示(这是实际问题):

  1. 时间 A 的线性运动,物体以恒定速度运动
  2. 时间 B 没有运动,物体停止
  3. 在 1 处重复。

谢谢!

编辑:好的换句话说:想象一辆汽车以匀速行驶 A 分钟,然后停下 B 分钟。然后再次行驶 A 分钟并再次停止 B 分钟。

时间 X 的汽车在哪里?

4

6 回答 6

2

好的,如果我理解正确:

int position(int time)
{
    int count_of_AB_cycles = time / (A + B);
    int time_in_current_cycle = time % (A + B);
    int time_moved_this_cycle = (time_in_current_cycle < A) ? time_in_current_cycle : A;
    int total_time_moving = (count_of_AB_cycles * A) + time_moved_this_cycle;
    return total_time_moving * speed;
}

假设整数除法等 -floor()如果 A 和 B 是非整数等,您将需要 s 。

于 2010-06-10T13:46:43.743 回答
1

就像是

int position(int t)
{
  static int pt = -1;
  static int px = 0;
  static int state = 1; // running...
  static int lastt = 0;
  if (pt < 0) { pt = t; lastt = t; }
  if ( state == 1 ) {
     if ( (t-pt) > A ) {
        state = 0;
        pt = t;
     }
  } else {
     if ( (t-pt) > B ) {
        state = 1;
        pt = t;
     }
  }
  px += state ? SPEED*(t-lastt) : 0; // advance
  lastt = t;
  return px;
}

编辑 上一个代码使用的评论

该代码旨在用于“运行时间”:它不会给出任何结果,只要时间 t 一劳永逸。每次调用该函数时,它被编程为虚拟地“移动”汽车一步,具体取决于前一次调用所经过的时间。适用于“游戏”,其中函数在每个“滴答”左右被调用,并且汽车的位置必须随着滴答的增加而更新,以便可以在当前位置上逐个滴答地在屏幕上绘制.

如果 OP 问题是关于知道汽车在时间 t 的位置,“数学上”,其他解决方案是好的解决方案(另外,请阅读我对该问题的第二条评论)

于 2010-06-10T13:59:27.410 回答
1

由于您提供的信息有限,没有比这更具体的了

return x * THE_SPEED

可以建议。

第二个条件可能旨在作为返回值的最大值,但如果没有上下文就很难判断。

第三个规范让我感到困惑。

于 2010-06-10T13:39:29.313 回答
0

对于前两个时间间隔,您可以这样做:

time = min(time, TIME_INTERVAL_A);
return time * CONST_SPEED;

这将导致您的对象在时间间隔 A 内以恒定速度行进,然后停止。

于 2010-06-10T13:45:28.120 回答
0

我不确定我是否正确理解了您的问题,但是您想要这样的东西吗?

(假设 C)

int position(int time)
{
    static int x = 0;
    x += time * SPEED;
    return x;
}
于 2010-06-10T13:46:22.813 回答
0

如果我理解正确,您有一个物体以恒定速度移动一段时间,然后停止,然后再次开始(以相同的速度?),然后停止,然后开始,等等?它沿着一维路径移动,因此与原点的距离是您唯一感兴趣的输出?

我建议您定义一个名为的辅助函数speedAt(time T),它可能类似于:

if 0 < T <= 25 then 5;
if 25 < T <= 32 then 0;
if 32 < T <= 47 then 3;
if 47 < T <= 49 then 0;
if 49 < T <= 125 then 1;
if 125 < T then 0.

现在你需要做的是整合这个函数来推导在时间 T 行进的距离,它由 T 的图形和水平轴之间的区域表示(在 xy 图中)。

由于这不是可微分或连续函数,因此您无需进行任何困难的数学运算,因此可以非常轻松地进行数值积分。有点像这样:

distanceTravelled = 0
for t = 1 to T
   distanceTravelled = distanceTravelled + speedAt(t)
end

这对你来说可能看起来有点乱。一种更复杂的方法是从数据结构中获取 speedAt 的值,但我希望你能明白。

于 2010-06-10T13:55:51.157 回答