给移动物体指明方向

时间:2017-08-08 12:42:28

标签: math sdl

我希望在SDL中创建塔防游戏。在开始这个项目之前,我会尝试编写游戏时需要做的所有事情。在我正在进行的测试中,有一个塔(静态物体),在其范围内的目标(移动物体),以及从炮塔发射到目标的射击(移动物体)。 我没有做的是找到一种方法来拍摄'拍摄'反对方向。通过射击物体,我的意思是当目标在范围内时由塔发射的物体。此外,无论方向如何,射击应始终具有相同的速度,禁止使用公式dirx = x2 - x1

射击是定义如下的结构:

typedef struct shoot
{
    SDL_Surface *img; // Visual representation of the shoot object.
    SDL_Rect pos;     // Position of the object, it's a structure containing
                      // coordinates x and y (these are of type int).
    int index;
    float dirx;       // dirx and diry are the movement done by the shoots object in
                      // 1 frame, so that for each frame, the object shoot is moved dirx
                      // pixels on the axis x and diry pixels on the axis y
    float diry;       // (the program deals with the fact that the movement will be done
                      // with integers and not with floats, that is no problem to me)
    float posx;       // posx and posy are the real, precise coordinates of the shoot
    float posy;
    struct shoot *prev;
    struct shoot *next;
} shoot;

我需要的是一种计算下一帧物体拍摄位置的方法,给出它在当前帧中的位置和方向。

这是我能找到的最好的(请注意,它是一个纸质书面公式,所以名称是简化的,与代码中的名称不同):

  • dirx = d * ((p2x - p1x) / ((p2x - p1x) + (p2y - p1y)))
  • diry = d * ((p2y - p1y) / ((p2x - p1x) + (p2y - p1y)))

    1. dirxdiry对应于像素中通过轴x和y上的拍摄在一帧中完成的移动。
    2. d是一个乘数,大括号(所有不是d)都是系数。
    3. p2是射击所针对的目标(目标的中心目标)。 p1是拍摄对象的当前位置。 xy表示我们使用该点的坐标x或y。

这个公式的问题在于它给了我一个不确定的值。例如,瞄准对角线会使拍摄速度变慢,直接瞄准北方。而且,它没有朝着正确的方向前进,我无法找到原因,因为我的论文测试表明我是对的...

我想在这里找到一些帮助,找到一个让拍摄正确移动的公式。

1 个答案:

答案 0 :(得分:6)

如果p1shoot对象的来源,则p2是目的地,而s是您想要移动它的速度(每帧单位或每秒 - 后者更好),然后对象的速度

给出
float dx = p2.x - p1.x, dy = p2.y - p1.y,
      inv = s / sqrt(dx * dx + dy * dy);
velx = inv * dx; vely = inv * dy;

(您应该将dir更改为vel,因为这是一个更明智的变量名称)

您的尝试似乎是通过曼哈顿距离对方向向量进行归一化,这是错误的 - 您必须通过 Euclidean距离进行归一化,这由{{1期限。

相关问题