开发者

Help with vectors

I'开发者_开发问答m trying to make a game where the bullets can fly in any direction. I would ike to make them vectors with a direction and magnitude to make them go the direction. I'm just not sure how to implement this?

Thanks


There are two parts that need to be calculated. First, I'd start off with the total distance. This should be straightforward:

total_distance = velocity * time

Assuming this is a 2D game, you should then use sine & cosine to break the total distance up into the X and Y components (for a given angle):

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

Finally, the distance x/y should be offset based on the starting position of the bullet:

pos_x = distance_x + start_pos_x
pos_y = distance_y + start_pos_y

Of course, you could wrap all of this in a nice class, expanding & polishing as needed.


You could have a bullet class which contains a position, direction vector, and a velocity. Every time step you could update the bullet's position like so:

position += direction * veclocity;

This assumes that the direction was a unit vector.


I would create start with something like this:

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;
}

You can then update your Bullet position with bullet.position += velocity (vector addition is done by adding the the components separately). Note, that the velocity vector contains both, the direction and the speed (=magnitude of the vector).

And if your Bullet should become slower every frame, you can do something like bullet.velocity *= 0.98 (where 0.98 represents the fraction). Vector multiplication with a scalar is done by multiplying each component with the scalar...

Regards, Christoph


this any use?

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

google is a wonderful tool

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜