我想在 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)))
dirx
并diry
对应于在一帧中由 x 轴和 y 轴上的拍摄在像素中完成的移动。d
是一个乘数,大括号(所有不是的d
)是一个系数。p2
是射击的目标点(目标的中心)。p1
是拍摄对象的当前位置。x
或y
表示我们使用点的坐标 x 或 y。这个公式的问题在于它给了我一个不准确的值。例如,在对角线瞄准会使射击比直接向北瞄准更慢。此外,它没有朝着正确的方向发展,我找不到原因,因为我的纸笔测试表明我是对的......
我很想在这里找到一些可以让拍摄正确移动的公式。
如果p1
是shoot
对象的来源,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
因为它是一个更合理的变量名称)
您的尝试似乎是通过曼哈顿距离标准化方向向量,这是错误的 - 您必须通过欧几里得距离标准化,这是由sqrt
术语给出的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句