jmasterx
jmasterx

Reputation: 54113

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

Upvotes: 1

Views: 441

Answers (4)

Eric Pi
Eric Pi

Reputation: 1924

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.

Upvotes: 1

pm100
pm100

Reputation: 50140

this any use?

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

google is a wonderful tool

Upvotes: 0

tux21b
tux21b

Reputation: 94659

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

Upvotes: 1

Kyle Lutz
Kyle Lutz

Reputation: 8036

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.

Upvotes: 1

Related Questions