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

Author Topic: Ghost Entries Inside The Vector!!  (Read 658 times)

0 Members and 1 Guest are viewing this topic.

samartheory

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
Ghost Entries Inside The Vector!!
« on: June 23, 2022, 11:12:27 pm »
So I am just getting started with SFML, and trying to make a simple physics engine. While creating multiple objects of a custom struct (which contains sf::CircularShape and some other variables) whenver I press the left key button it should create a new object of my custom class and push it to a vector and at the end of this journey the vector should have the its size equal to 1 (vector.size() = 1) but instead the size increases by greater than 1 that means I am getting some entries from idk where

       //verlet is the custom struct
        vector<verlet> all;
        float radius = 50.f;
        //event loop / game loop
        while (window.isOpen())
        {
                sf::Event ent;
                //if there are any pending events
                while (window.pollEvent(ent))
                {
                        if (ent.type == sf::Event::Closed)
                                window.close();
                }
                //to create a circle
               //*********THE BELOW IF STATEMENT IS CREATING PROBLEM******************
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                {
                        sf::Vector2i localPosition = sf::Mouse::getPosition(window);
                        verlet cir(radius, (sf::Vector2f)localPosition);
                        all.push_back(cir);
                }
                //clear all circles
     
                else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
                {
                        all.clear();
                }

               
       
                window.clear();
                cout << all.size() << endl;
                window.draw(ground);
                window.display();
        }
 

Any help will be appreciated!

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10819
    • View Profile
    • development blog
    • Email
Re: Ghost Entries Inside The Vector!!
« Reply #1 on: June 24, 2022, 06:44:12 pm »
Say if you have limited your frame rate at 60fps, that means the main loop will iterate 60 times per second.
Now if you press a key, the isKeyPressed will return true and you'll add a new shape every iterations.
That means, unless you manage to press the key for less than ~16ms, you'll always get more than one entry.

I personally, recommend to use events instead. And if you want to limit it to one key press & release cycle, then you'll need to track the key state.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/