Thread: Problem with std lists and my ships

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    42

    Problem with std lists and my ships

    I'm not sure what the cause of this problem is.

    I'm working on a space shooter for practice.

    I have a list called "object" of all the ships and weapon shots that are active (in my implimetation, weapon shots are just ships that go straight and crash with other ships).

    I also have a list called "destroying". This contains ships that have been destroyed by weapons fire. Ships in "destroyed" are in the process of displaying their explosion graphic and will be removed from the game once it's done. They also have their AI disabled.

    In my code, when any ship is destroyed, it is immediately added to the destroying list and removed from the object list. I don't know why, but it crashes. I'm guessing it's in the implimentation of the list (and I absolutely hate the std list and don't know why I didn't just make my own class). Where am I going wrong?

    Code:
        for(list<Entity*>::iterator ptr = object.begin(); ptr != object.end(); ptr++)
        {
            for(list<Entity*>::iterator targ = ptr; targ != object.end(); targ++)
            {
                //once a collision occurs, it seems to crash at this point
                if((*ptr)->collision(*targ)) //if they hit, check for destruction
                {
                    if((*ptr)->destroyed())
                    {
                        destroying.push_front(*ptr);
                        object.erase(ptr);
                    }
                    if((*targ)->destroyed())
                    {
                        destroying.push_front(*targ);
                        object.erase(targ);
                    }
                }
            }
        }

  2. #2
    Registered User
    Join Date
    Jan 2003
    Posts
    42
    Never mind. I figured it out! I just made this tiny change after reading the list functions more carefully at cppreference.com.

    Code:
                    if((*ptr)->destroyed())
                    {
                        destroying.push_front(*ptr);
                        ptr = object.erase(ptr);
                    }
                    if((*targ)->destroyed())
                    {
                        destroying.push_front(*targ);
                        targ = object.erase(targ);
                    }

Popular pages Recent additions subscribe to a feed