给移动物体指明方向

nou*_*oir 0 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;
Run Code Online (Sandbox Code Playgroud)

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

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

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

    1. dirx并且diry对应于像素中通过轴x和y上的拍摄在一帧中完成的移动.
    2. d是一个乘数,大括号(所有不是d)是一个系数.
    3. p2射击应该瞄准的目标(目标的中心目标).p1是拍摄对象的当前位置.x或者y意味着我们使用点的坐标x或y.

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

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

meo*_*dog 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;
Run Code Online (Sandbox Code Playgroud)

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


你的尝试似乎是按曼哈顿距离标准化方向向量,这是错误的 - 你必须通过欧几里德距离归一化,这是由sqrt术语给出的.