Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [SOLVED]Assigning a direction to bullets from a vector  (Read 11027 times)

0 Members and 1 Guest are viewing this topic.

bumblecorn

  • Newbie
  • *
  • Posts: 18
    • View Profile
[SOLVED]Assigning a direction to bullets from a vector
« on: February 08, 2013, 07:29:32 pm »
I have multiple bullets spawning from a vector, as long as a button is pressed, but there's a little problem with the direction. The already fired bullets also change movement when the direction is changed.
Pseudo code, I don't have the project on me right now:

vector<ProjectileClass> bullets;

//this is in my main loop-------------
if (button is pressed)
                {
                        bullets.push_back(projectile); //projectile is the object created from the ProjectileClass
                        shooting();
                }

//the "shooting" function------------
int shooting()
{
//here I'm getting the direction
        movementX = getJoystickX
        movementY = getJoystickY
               
        return 0;
}

//this function is called later in the main loop to draw and move the bullets
int ShootMove()
{
        for (int i = 0; i < bullets.size(); ++i)
        {
                window.draw(bullets[i]);
                bullets[i].move(movementX/2, movementY/2);
        }
        return 0;
}


Now what I want to achieve is to have a constant stream of bullets fired into the direction the player object is pointing at. But as you can see, while the button is pressed the movementX/Y variables are updated on each loop, influencing the already fired bullets. Is there a way I can store the movement for each object spawned from the vector?

« Last Edit: February 10, 2013, 08:53:37 pm by bumblecorn »

Weeve

  • Jr. Member
  • **
  • Posts: 87
  • C++ Programmer (Intermediate), 3D Artist (Skilled)
    • View Profile
    • Email
Re: Assigning a direction to bullets from a vector
« Reply #1 on: February 08, 2013, 08:35:03 pm »
you could store the trajectory vector inside of ProjectileClass, and copy movementX and movementY into it on creation of the bullet, then just move each bullet by ProjectileClass's movement vector, example:

if (button is pressed)
        {
            shooting();// first, so that you get new movement values to use
            bullets.push_back(projectile(movementX/2, movementY/2));
            // have ProjectileClass's constructor copy the two floats to TrajectoryX and TrajectoryY
            // which should be public variables, as information hiding is not usefull here, and make syntax easier
        }


int ShootMove()
{
        for (int i = 0; i < bullets.size(); ++i)
        {
                window.draw(bullets[i]);
                bullets[i].move(bullets[i].TrajectoryX, bullets[i].TrajectoryY);
        }
        return 0;
}
 
Long live rapid project development! -- Kestrel3D Game-Engine nearing completion

bumblecorn

  • Newbie
  • *
  • Posts: 18
    • View Profile
Re: Assigning a direction to bullets from a vector
« Reply #2 on: February 10, 2013, 08:52:56 pm »
Thanks, got it sorted out in no time :D

masskiller

  • Sr. Member
  • ****
  • Posts: 284
  • Pointers to Functions rock!
    • MSN Messenger - kyogre_jb@hotmail.com
    • View Profile
    • Email
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #3 on: February 10, 2013, 10:10:56 pm »
An alternative is to use a polar vector, a polar vector uses an angle and a radius, so you can perfectly calculate an angle and just increase the radius in order to generate linear movement, in order to generate curved movement you can just modify the angle, or modify them both and you get your desired movement in a nice looking notation.

That way you can have linear movement with only one speed instead of two (unless movement is curved, where you'll need an angle offsetting value as well).
Programmer, Artist, Composer and Storyline/Script Writer of "Origin of Magic". If all goes well this could turn into a commercial project!

Finally back into the programming world!

Roose Bolton of the Dreadfort

  • Full Member
  • ***
  • Posts: 113
  • Full-time Procrastinator, Part-time programmer.
    • View Profile
    • Personal Portfolio/Website/Blog
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #4 on: February 13, 2013, 11:35:46 am »
creating new bullets everytime the button is pressed isn't a good way to go about it is?

I have always been taught to use a 'BulletManager' that has a pool of say 200 bullets which are allocated when the level loads, it then assigns them to whatever entity is firing a bullet... then once the bullet hits a wall or a target it goes back to inactive and can then be reassigned to another shooting entity....

Trying so very hard to finish at-least one project.

Watch out for the RAII police, they will get you.

www.bantersaurus-games.com

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #5 on: February 13, 2013, 11:56:26 am »
creating new bullets everytime the button is pressed isn't a good way to go about it is?
Yes, it's a good way. It's the most intuitive way, and unless you have a strong reason against it, you should always keep things simple.

I have always been taught to use a 'BulletManager' that has a pool of say 200 bullets which are allocated when the level loads, it then assigns them to whatever entity is firing a bullet... then once the bullet hits a wall or a target it goes back to inactive and can then be reassigned to another shooting entity....
This implies a lot of complexity for probably no gain. It is a phenomenon among game developers that they use "managers" and "engines" for everything and believe that things are terribly object-oriented and magically improve.

Seriously, the additional complexity only pays off if the time to create and destroy bullets is significantly high in relation to other program parts. Unless you can prove it is (by measuring), avoid premature optimization and keep your code simple and understandable.
« Last Edit: February 13, 2013, 11:58:19 am by Nexus »
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

Roose Bolton of the Dreadfort

  • Full Member
  • ***
  • Posts: 113
  • Full-time Procrastinator, Part-time programmer.
    • View Profile
    • Personal Portfolio/Website/Blog
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #6 on: February 13, 2013, 12:27:52 pm »
creating new bullets everytime the button is pressed isn't a good way to go about it is?
Yes, it's a good way. It's the most intuitive way, and unless you have a strong reason against it, you should always keep things simple.

I have always been taught to use a 'BulletManager' that has a pool of say 200 bullets which are allocated when the level loads, it then assigns them to whatever entity is firing a bullet... then once the bullet hits a wall or a target it goes back to inactive and can then be reassigned to another shooting entity....
This implies a lot of complexity for probably no gain. It is a phenomenon among game developers that they use "managers" and "engines" for everything and believe that things are terribly object-oriented and magically improve.

Seriously, the additional complexity only pays off if the time to create and destroy bullets is significantly high in relation to other program parts. Unless you can prove it is (by measuring), avoid premature optimization and keep your code simple and understandable.

So in your opinion, creating and destroying hundreds and hundreds of bullets realtime on the stack is okay?

Heh, I always thought it caused performance issues... perhaps I was doing something wrong.

Not just that, but the larger your game gets, and if you keep calling objects everytime you need them (spawning bullets, entities, explosions etc) on the stack.. im sure eventually you will hit stack overflow.
« Last Edit: February 13, 2013, 12:35:47 pm by Tally »
Trying so very hard to finish at-least one project.

Watch out for the RAII police, they will get you.

www.bantersaurus-games.com

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #7 on: February 13, 2013, 12:52:04 pm »
So in your opinion, creating and destroying hundreds and hundreds of bullets realtime on the stack is okay?
Not on the stack, but yes. Today's computers can handle complex 3D physic simulations. The creation of a few bullets per frame can't be an issue, unless you do something terribly wrong.

It is of course recommended to model bullets as light-weight entities, maybe even pure logic occupying only a few bytes (like position + velocity).

Not just that, but the larger your game gets, and if you keep calling objects everytime you need them (spawning bullets, entities, explosions etc) on the stack.. im sure eventually you will hit stack overflow.
Who says I put them on the stack? You want bullets to outlive the local scope, so you need dynamic storage anyway. Just insert the objects into STL containers. Don't make life more complicated than necessary with pools, they have very specific use cases and should certainly not be the standard approach.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

Roose Bolton of the Dreadfort

  • Full Member
  • ***
  • Posts: 113
  • Full-time Procrastinator, Part-time programmer.
    • View Profile
    • Personal Portfolio/Website/Blog
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #8 on: February 13, 2013, 01:23:46 pm »
So in your opinion, creating and destroying hundreds and hundreds of bullets realtime on the stack is okay?
Not on the stack, but yes. Today's computers can handle complex 3D physic simulations. The creation of a few bullets per frame can't be an issue, unless you do something terribly wrong.

It is of course recommended to model bullets as light-weight entities, maybe even pure logic occupying only a few bytes (like position + velocity).

Not just that, but the larger your game gets, and if you keep calling objects everytime you need them (spawning bullets, entities, explosions etc) on the stack.. im sure eventually you will hit stack overflow.
Who says I put them on the stack? You want bullets to outlive the local scope, so you need dynamic storage anyway. Just insert the objects into STL containers. Don't make life more complicated than necessary with pools, they have very specific use cases and should certainly not be the standard approach.

Well he declares them as local objects, so they will be managed on the stack, or am I wrong? How does putting them into an stl container change the fact of what memory they are allocated on?

If he uses new/delete etc, then they will be handled on the heap.

I am just going by past experiences, when declaring bullets over and over (hundreds and hundreds) I get performance hits over having a pool of bullets which there is none. Although I think the objects where quite large...

Cheers for tip Nexus..
« Last Edit: February 13, 2013, 01:27:08 pm by Tally »
Trying so very hard to finish at-least one project.

Watch out for the RAII police, they will get you.

www.bantersaurus-games.com

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #9 on: February 13, 2013, 01:31:39 pm »
Well he declares them as local objects, so they will be managed on the stack, or am I wrong? How does putting them into an stl container change the fact of what memory they are allocated on?
The STL container can of course be no local variable, otherwise it would be destroyed at the end of the scope. It is rather a member variable of the surrounding class (but not allocated with new).

If you insert objects into an STL container except std::array, they are stored dynamically (on the freestore/heap), independently of the STL container's own storage class. In modern C++, using directly new and delete to manage memory is almost always a mistake. One should prefer RAII instead.

And please stop full-quoting, especially when the referred post is just above. It makes threads very unreadable.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

Roose Bolton of the Dreadfort

  • Full Member
  • ***
  • Posts: 113
  • Full-time Procrastinator, Part-time programmer.
    • View Profile
    • Personal Portfolio/Website/Blog
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #10 on: February 13, 2013, 01:43:45 pm »
Quote
The STL container can of course be no local variable, otherwise it would be destroyed at the end of the scope. It is rather a member variable of the surrounding class (but not allocated with new).

If you insert objects into an STL container except std::array, they are stored dynamically (on the freestore/heap), independently of the STL container's own storage class. In modern C++, using directly new and delete to manage memory is almost always a mistake. One should prefer RAII instead.

Okay. So how do you go about destroying the bullets? using the Erase function in the std::vector?
Trying so very hard to finish at-least one project.

Watch out for the RAII police, they will get you.

www.bantersaurus-games.com

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #11 on: February 13, 2013, 02:24:38 pm »
It depends on the STL container. std::vector::erase() has the problem that it takes linear time (all elements after it have to be moved one element back). So, if you use it in a loop, you have quadratic time complexity. There is a trick to have constant time removal in vectors: Swap the element to remove with the last one and call pop_back().

Alternatively, if there are multiple elements to remove each frame, the STL algorithms std::remove() and std::remove_if() are helpful:
auto itr = std::remove_if(bullets.begin(), bullets.end(), std::mem_fn(&Bullet::isDead));
bullets.erase(itr, bullets.end());
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

bumblecorn

  • Newbie
  • *
  • Posts: 18
    • View Profile
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #12 on: February 14, 2013, 05:52:36 pm »
I love how after I marked it as [SOLVED] it suddenly got popular. Anyway new problem. The direction and everything is working fine, thanks again Weeve, but what I want to do now is to DELAY the bullets fired i.e. I hold down the fire button, but it doesn't create a constant stream, rather a new bullet is created every 0.5 seconds.
At the moment it pretty much looks like a stationary dotted line, when fired in one direction.

I'm thinking one simple way to do this is to calculate the distance between the previously fired bullet and the player and if it is lesser than, say 100 pixels, don't fire the bullet. Or is there a better way of doing it? I guess now if you back up, or accelerate towards the bullet it will impact the "recharge" time.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #13 on: February 14, 2013, 06:09:10 pm »
Or is there a better way of doing it?
Yes, measure time. Not real time, but game time. You specify an interval to shoot bullets, for example
const sf::Time interval = sf::Milliseconds(200);

Then, you accumulate the frame time dt (which can be constant or variable) in a counter. If a certain value is reached, reset the accumulator and fire a bullet.
sf::Time accumulator; // member variable
accumulator += dt;

if (accumulator > interval) // or while, if it may happen that frames take that long
{
    accumulator -= interval;
    fireBullet();
}

Measuring distance is a bad idea, because it depends on the relative velocity of the bullet with respect to the player. Also, you need to keep track of the most recently fired bullet.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

bumblecorn

  • Newbie
  • *
  • Posts: 18
    • View Profile
Re: [SOLVED]Assigning a direction to bullets from a vector
« Reply #14 on: February 14, 2013, 07:33:05 pm »
I wasn't sure what you meant by frame time "dt", so I went ahead and did something a bit different:

int accumulator = 0; //just declaring outside the main loop

accumulator = accumulator + 1;

        if (sf::Joystick::isButtonPressed(0, 5) && accumulator > 20)
        {
                accumulator = 0;
                shooting(movementX, movementY, rightStickX, rightStickY);
                bullets.push_back( Projectiles( you.getPosition().x, you.getPosition().y, 10, 10, movementX/2, movementY/2 ) ); //nvm the params
        }

Every time the loop runs it adds "1" to the accumulator. Then, if it's above 20 && the button is pressed it will reset the accumulator and push a bullet to the vector etc.
Works fine, but is this in any way inferior to your method? It seems a helluva lot simpler :D