1

我正在尝试制作一个子弹可以向任何方向飞行的游戏。我想让它们成为具有方向和大小的向量,以使它们朝着这个方向前进。我只是不确定如何实现这个?

谢谢

4

4 回答 4

1

你可以有一个包含位置、方向向量和速​​度的子弹类。每一步你都可以像这样更新子弹的位置:

position += direction * veclocity;

这假设方向是单位向量。

于 2010-02-12T01:59:02.427 回答
1

我会从这样的东西开始创建:

struct Vector3f {
    float x, y, z;
};

struct Bullet {
    Vector3f position;
    Vector3f velocity;
};

inline const Vector3f& Vector3f::operator+=(const Vector &other)
{
    x += other.x;
    y += other.y;
    z += other.z;
    return *this;
}

inline const Vector3f& Vector3f::operator*=(float v)
{
    x *= v;
    y *= v;
    z *= v;
    return *this;
}

然后您可以更新您的子弹位置bullet.position += velocity(矢量添加是通过单独添加组件来完成的)。请注意,速度矢量包含方向和速度(=矢量的大小)。

如果您的 Bullet 每帧都变慢,您可以执行类似的操作bullet.velocity *= 0.98(其中 0.98 代表分数)。向量与标量的乘法是通过将每个分量与标量相乘来完成的...

问候,克里斯托夫

于 2010-02-12T02:04:30.287 回答
1

有两个部分需要计算。首先,我将从总距离开始。这应该很简单:

total_distance = velocity * time

假设这是一个 2D 游戏,那么您应该使用正弦和余弦将总距离分解为 X 和 Y 分量(对于给定的角度):

distance_y = total_distance * sin(2 * pi * angle / 360)
distance_x = total_distance * cos(2 * pi * angle / 360)

最后,距离 x/y 应该根据子弹的起始位置进行偏移:

pos_x = distance_x + start_pos_x
pos_y = distance_y + start_pos_y

当然,您可以将所有这些封装在一个不错的类中,并根据需要进行扩展和完善。

于 2010-02-12T02:10:29.090 回答
0

这有什么用?

http://www.cs.cmu.edu/~ajw/doc/svl.html

google 是一个很棒的工具

于 2010-02-12T02:10:28.817 回答