mardi 23 juin 2020

C++ Class Method Return Different Values

I have encountered a weird error within my code. I have tried to attach as much code relevant code below as possible. On the very first bullet-asteroid collision(commented below) during runtime within my AsteroidManager::collide(...) method, a different value is returned for Asteroid::getSize() after the first call of spawnAsteroid(). I never set the size anywhere in spawnAsteroid() and this only happens once during runtime. All collision that happen afterward work as expected. I will provide additional code if requested.

class Asteroid
{
private:
    ...
    GLint size;

public:
    Asteroid(const glm::vec3& pos, const glm::vec3& pos_vel, GLfloat rot, GLfloat rot_vel, GLint size);
    ...
    inline GLint getSize(void) const { return size; } // This method returns different value?
    inline void setSize(GLint size) { this->size = size; }
    ...
};

Below is the snippets of code relevant to the error.

void AsteroidManager::spawnAsteroid(const glm::vec3& pos, GLint size)
{
    ... // size is not modified
    asteroids.push_back(Asteroid(glm::vec3(...), glm::vec3(...), rotation, rotationVelocity, size));
}

void AsteroidManager::spawnAsteroids(GLint width, GLint height) // I use this to initialize the objects, everything works fine
{
    for (size_t i = 0; i < 1; i++)
    {
        GLfloat x = std::rand() % width;
        GLfloat y = std::rand() % height;
        spawnAsteroid(glm::vec3(x, y, 0.0f), 3); // works fine
    }
}

void AsteroidManager::collide(BulletManager& bullets)
{
    for (auto& asteroid : asteroids)
    {
        for (auto& bullet : bullets.getBullets())
        {
            // Collision Testing
            if (bullet.isActive() && asteroid.isActive() && Circle(asteroid.getPosition().x, asteroid.getPosition().y, asteroid.getSize() * 14.0f).testCollision(Point(bullet.getPosition().x, bullet.getPosition().y)))
            {
                bullet.setActive(false);
                asteroid.setActive(false);
                if (asteroid.getSize() > 1)
                {
                    // On the very first bullet-asteroid collision in the entire program
                    // asteroid.getSize() returns the wrong value after the first spawnAsteroid() call
                    // The second SpawnAsteroid call gets a different size.
                    // This only happens on the first collision during entire runtime.
                    spawnAsteroid(asteroid.getPosition(), asteroid.getSize() - 1);
                    spawnAsteroid(asteroid.getPosition(), asteroid.getSize() - 1); // Wrong size returned here?! Should be 2 not -572662308
                }
                break;
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire