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

Author Topic: Create unlimited amount of bullets  (Read 4702 times)

0 Members and 1 Guest are viewing this topic.

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Create unlimited amount of bullets
« on: January 02, 2014, 06:34:18 pm »
Hello.
I previously had a static array where i entered the max amount of bullets as the size of array, for example 100. But i guess this isn't such a good approach for many things where the array size varies, so i heard vectors were a good option instead of arrays because you don't need to memory manage them like with a dynamic array.

But now i need some help in how i'm supposed to use the vector. This is what i have so far. it crashes when it goes into the function newBullet. The problem right now is that the bullet will not be affected by the box2d world. Gravity for example wont affect it.



struct sBox{
    b2BodyDef myBodyDef;
    b2Body* body;
    b2PolygonShape boxShape;
    b2FixtureDef boxFixtureDef;
    sf::RectangleShape Rect;
};

struct sBullet{
    int airTime;
    sf::Vector2f targetVector;
    float toTargetAngle;
    float speed;
    sBox box;
    sf::Sprite Sprite;
};

struct sCharacter{
    std::vector<sBullet> bullet;
    sf::Vector2f targetVector;
    float toTargetAngle;
    int castTime;
    float degreeAngle;;
    int bulletCooldown;
    };
sCharacter character;

void newBullet(sCharacter *character, int PPM, b2World *world, sf::Texture *Texture, sf::Vector2i worldMouseClick, sf::Vector2f position, sf::Vector2f boxSize){
        sBullet bullet;
        character->bullet.push_back(bullet); //+1 to array

        //Calculate bullet path and angle
        character->bullet.back().targetVector.x = worldMouseClick.x - position.x;
        character->bullet.back().targetVector.y = worldMouseClick.y - position.y;
        character->bullet.back().toTargetAngle = atan2(character->bullet.back().targetVector.y, character->bullet.back().targetVector.x);

        //Bullet duration and cooldown
        character->bullet.back().airTime = 500;
        character->bulletCooldown = 20;

        //Set box2d value + spawn body
        character->bullet.back().box.myBodyDef.type = b2_kinematicBody; //this will be a kinematic body
        character->bullet.back().box.myBodyDef.position.Set(position.x/PPM, position.y/PPM); //set the starting position
        character->bullet.back().box.myBodyDef.angle = 0; //set the starting angle
        character->bullet.back().box.body = world->CreateBody(&character->bullet.back().box.myBodyDef);
        character->bullet.back().box.boxShape.SetAsBox(boxSize.x/PPM/2, boxSize.y/PPM/2);
        character->bullet.back().box.boxFixtureDef.shape = &character->bullet.back().box.boxShape;
        character->bullet.back().box.boxFixtureDef.density = 1;
        character->bullet.back().box.body->CreateFixture(&character->bullet.back().box.boxFixtureDef);

        character->bullet.back().box.body->SetActive(true);

        //Set bullet sprite
        character->bullet.back().Sprite.setTexture(Texture[9]);
        character->bullet.back().Sprite.setOrigin(character->bullet.back().Sprite.getLocalBounds().width -20, character->bullet.back().Sprite.getLocalBounds().height / 2);
};

int main(int argc, char** argv){

b2Vec2 gravity(0, 0); //normal earth gravity, 9.8 m/s/s straight down!
b2World* world = new b2World(gravity);
world->SetAllowSleeping(true);


//Bullet Cast time
if (character.castTime >= 0){
    character.castTime -= 1;
}
//Bullet Cooldown
if (character.bulletCooldown > 0){
character.bulletCooldown -= 1;
}

//Start bullet cast
if (mouseOnInventory == false && itemMousePos == -1 && itemOnMouse == -1 && leftButtonDown == 1 && character.castTime == -1 && character.bulletCooldown == 0 && character.currentMana >= character.bullet[0].manaCost){
            worldMouseClick = worldMouse; //Save click pos
            character.castTime = 20;
            character.currentMana -= character.bullet[0].manaCost;
            //Set only character angle
            character.targetVector.x = worldMouseClick.x - Character.getPosition().x;
            character.targetVector.y = worldMouseClick.y - Character.getPosition().y;
            character.toTargetAngle = atan2(character.targetVector.y, character.targetVector.x);
            character.degreeAngle = character.toTargetAngle * 180 / PI;
}

//Fire bullet
if (character.castTime == 0){
            newBullet(&character, PPM, world, Texture, worldMouseClick, Character.getPosition(), sf::Vector2f(40, 40));
            character.bullet.back().box.body->SetTransform(b2Vec2(Character.getPosition().x/PPM, Character.getPosition().y/PPM), character.bullet.back().toTargetAngle);
}
//Set bullet pos
for (int i = 0; i < character.bullet.size(); i++){
        character.bullet[i].box.body->SetLinearVelocity(b2Vec2(cos(character.bullet[i].toTargetAngle)*character.bullet[0].speed, sin(character.bullet[i].toTargetAngle)*character.bullet[0].speed));
}


//Remove bullet after a certain time
for (int i = 0; i < character.bullet.size(); i++){
    if (character.bullet[i].airTime > 0)
        character.bullet[i].airTime -= 1;

    else{
        character.bullet[i].box.body->SetActive(false);
        character.bullet.erase(character.bullet.begin() + i-1);
    }
}

//Box2d
float32 timeStep = 1/60.0;      //the length of time passed to simulate (seconds)
int32 velocityIterations = 10;   //how strongly to correct velocity
int32 positionIterations = 6;   //how strongly to correct position
//Update world. This needs to come after you set positions and before you try to get current positions values.
world->Step(timeStep, velocityIterations, positionIterations);

//Set positon of sprites.
for (int i = 0; i < character.bullet.size(); i++){
character.bullet[i].Sprite.setPosition(character.bullet[i].box.body->GetPosition().x*PPM, character.bullet[i].box.body->GetPosition().y*PPM);
character.bullet[i].Sprite.setRotation(character.bullet[i].box.body->GetAngle()*RADTODEG);
}
}
« Last Edit: January 03, 2014, 07:24:59 pm by zippo88 »

amir ramezani

  • Jr. Member
  • **
  • Posts: 81
  • i'm a programmer who can't see well
    • View Profile
    • download useful software!
    • Email
Re: Create unlimited amount of bullets
« Reply #1 on: January 02, 2014, 08:52:01 pm »
all of your code is rong
firstly, you must declare a variable that hold's amount of bullets
after that, you have to declare 2 variables: boath are integers, that hold's x and y positions of the bullet
then you must do how the bullet can fire
for example, if x and y of the bullet is equal to x and y of the enummy, kill it and get a point
you have to declare a variable for point that hold's integer value
as i mentioned , all of your code is rong
if you can't see well, you can't test your applications and operating system well
my game engine:
allegro game creator
my operating system:
AmirOS

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #2 on: January 02, 2014, 09:15:57 pm »
all of your code is rong
firstly, you must declare a variable that hold's amount of bullets
after that, you have to declare 2 variables: boath are integers, that hold's x and y positions of the bullet
then you must do how the bullet can fire
for example, if x and y of the bullet is equal to x and y of the enummy, kill it and get a point
you have to declare a variable for point that hold's integer value
as i mentioned , all of your code is rong
The whole point of this was so i don't have to set a max amount of bullets. I did edit my code and got it running now atleast, but it got some issues i'm trying to resolve.

The biggest change was that
character->bullet.size()
needs to be
character->bullet.size()-1
because the vector starts at 0. I also had to change character to a pointer in the function so it saves the push_back.

I will edit with my changes. currently it just fires 1 bullet and it doesn't move anywhere.

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Re: Create unlimited amount of bullets
« Reply #3 on: January 02, 2014, 10:17:17 pm »
Use the member function std::vector::back().

And you should definitely encapsulate your data, this code will be extremely hard to maintain as soon as it grows...
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #4 on: January 02, 2014, 10:40:06 pm »
Use the member function std::vector::back().

And you should definitely encapsulate your data, this code will be extremely hard to maintain as soon as it grows...
Thanks. I'm not that good with the use of functions and classes yet so i will improve on it later on but i did what you said and am now using std::vector::back(). It is much cleaner, but the code remains the same. I'm not sure why but it only shoots 1 bullet, and that bullet stays at 1 spot.

This is the line to move the bullet, and this worked before i converted to vector so the math is there. it's something else.
//Set bullet pos
for (int i = 0; i < character.bullet.size(); i++){
        character.bullet[i].box.body->SetLinearVelocity(b2Vec2(cos(character.bullet[i].toTargetAngle)*character.bullet[0].speed, sin(character.bullet[i].toTargetAngle)*character.bullet[0].speed));
        character.bullet[i].Sprite.setPosition(character.bullet[i].box.body->GetPosition().x*PPM, character.bullet[i].box.body->GetPosition().y*PPM);
}

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #5 on: January 03, 2014, 12:46:25 am »
updated it to make sure the bullet doesn't spawn until it's supposed to. It still wont move though, not even if i set gravity in box2d. My testbox will be affected by the gravity though.

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10826
    • View Profile
    • development blog
    • Email
Re: Create unlimited amount of bullets
« Reply #6 on: January 03, 2014, 12:50:40 am »
I'm not that good with the use of functions and classes yet
Then you should first learn C++ properly. It's complex language and you won't get far with trial-and-error. Get a good C++ book and learn all about classes, functions and especially the STL! :)
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #7 on: January 03, 2014, 01:06:13 am »
I'm not that good with the use of functions and classes yet
Then you should first learn C++ properly. It's complex language and you won't get far with trial-and-error. Get a good C++ book and learn all about classes, functions and especially the STL! :)
Yes i plan to get a book, but for now i have none. But it's hard to learn everything perfectly on your own even with a book. Are you able to spot what the error in my code is? I've updated it quite a bit now since i first posted but i can't figure out why the bullet wont move.
« Last Edit: January 03, 2014, 01:26:25 am by zippo88 »

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10826
    • View Profile
    • development blog
    • Email
Re: Create unlimited amount of bullets
« Reply #8 on: January 03, 2014, 01:29:03 am »
But it's hard to learn everything perfectly on your own even with a book.
Yes, you won't get the needed experience just from reading books, that you'll have to acquire by coding, but you'll learn a lot more than just "hacking" away. ;)

Are you able to spot what the error in my code is? I've updated it quite a bit now since i first posted but i can't figure out why the bullet wont move.
Not really, because it's huge spaghetti-code, plus a lot of stuff is left out. Like the whole creation of the Box2D stuff or loading of the textures etc.
Also if you have 10 lines with the the same beginning (e.g. character->bullet.back()), chances are 99.9999999% that you're going wrong about things... which brings as back to learning about classes... ;)
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #9 on: January 03, 2014, 02:34:45 am »
But it's hard to learn everything perfectly on your own even with a book.
Yes, you won't get the needed experience just from reading books, that you'll have to acquire by coding, but you'll learn a lot more than just "hacking" away. ;)

Are you able to spot what the error in my code is? I've updated it quite a bit now since i first posted but i can't figure out why the bullet wont move.
Not really, because it's huge spaghetti-code, plus a lot of stuff is left out. Like the whole creation of the Box2D stuff or loading of the textures etc.
Also if you have 10 lines with the the same beginning (e.g. character->bullet.back()), chances are 99.9999999% that you're going wrong about things... which brings as back to learning about classes... ;)
Maybe it's spaghetti code, but it's MY spaghetti code :).

Well this is the only things box2d which was left out.
b2Vec2 gravity(0, 0); //normal earth gravity, 9.8 m/s/s straight down!
b2World* world = new b2World(gravity);
world->SetAllowSleeping(true);
This is in the main before the loop starts.

The reason why i haven't posted textures is that i have tested already if that is the issue, but the texture is in the right place. I set gravity and let a test box fall on my bullet sprite which doesn't move and the box2d bullet is in that same location.
Gravity does not affect my bullet box and setting velocity does not affect it either.
I had box2d working fine with bullets when i was using arrays with a set size.
« Last Edit: January 03, 2014, 02:39:08 am by zippo88 »

amir ramezani

  • Jr. Member
  • **
  • Posts: 81
  • i'm a programmer who can't see well
    • View Profile
    • download useful software!
    • Email
Re: Create unlimited amount of bullets
« Reply #10 on: January 03, 2014, 05:24:33 am »
you have to learn anything of vectors first
and then write your code
this code is very very very very very unreadable
I've not understand it!
the first thing that should a programmer do is to write a good and understandable code
i think if you start an Operating system project, your OS may not be worked
if you can't see well, you can't test your applications and operating system well
my game engine:
allegro game creator
my operating system:
AmirOS

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #11 on: January 03, 2014, 04:27:16 pm »
I don't see what the problem is with reading my code. You don't have to understand it completely. The only thing you need to know is that there's a problem with how i initialize the bullet. It gets added to the world, i've checked that with world->GetBodyCount(), and that it has collision with other boxes. But the world wont move it if i set velocity of the bullet and not even when i set gravity of the world.

Anyway i got a book now that i'm reading although i doubt it will help with this particular problem. This is more of a box2d issue i think at this point.

Edit: I'm not saying it's box2d's fault, i mean it's an issue of me not understanding how box2d needs to do things. If you want i can post the code of when the bullets + box2d did work.
« Last Edit: January 03, 2014, 04:29:02 pm by zippo88 »

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6286
  • Thor Developer
    • View Profile
    • Bromeon
Re: Create unlimited amount of bullets
« Reply #12 on: January 03, 2014, 06:20:55 pm »
I don't see what the problem is with reading my code
You should read that post, it summarizes everything :)
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #13 on: January 03, 2014, 07:19:48 pm »
I don't see what the problem is with reading my code
You should read that post, it summarizes everything :)
Ok i have now cleaned up the code a little more + removed everything that is unnecessary for this example. Unused variables mostly.

Voroz

  • Full Member
  • ***
  • Posts: 128
    • View Profile
Re: Create unlimited amount of bullets
« Reply #14 on: January 03, 2014, 07:46:24 pm »
Ok i solved it. I was multiplying the speed with character.bullet[0].speed, which worked before when that bullet was always declared in the array. Now it wasn't. I noticed it when only the first bullet costed any mana (i was also subtracting character.bullet[0].manaCost). So now that works, but there are some performance issues i think in that i always create new bodies to the world. I need to check somehow that if there is a free body to use it will use that one instead.
« Last Edit: January 03, 2014, 07:51:12 pm by zippo88 »

 

anything