Search code examples
xnamonogame

XNA game frozen


I was following a tutorial for creating a 2d space shooter. It was working fine until I added code to spawn enemy mobs, now it just runs but it's frozen. I can't understand why it wont work. there are no errors anywhere or anything like that.

Thanks.


Solution

  • You have a minor typo with the brackets in your update method.

    protected override void Update(GameTime gameTime)
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        //updating mobs and checking for collisions
        foreach (Mobs M in mobsList)
        {
            // Updating the mobs, collision checking, etc here
            ...
    
            ...
            Player.update(gameTime);
            bG.update(gameTime);
            loadAsteroids();
            loadMobs();
    
            foreach (Roids R in asteroidList)
            {
                // Updating the asteroids, collision checking, etc
                ...
    
                ...
                M.update(gameTime);
                R.update(gameTime);
            }
    
            base.Update(gameTime);
        }
    }
    

    There are two main things wrong in this. Firstly, this bit of code:

    Player.update(gameTime);
    bG.update(gameTime);
    loadAsteroids();
    loadMobs();
    
    foreach (Roids R in asteroidList)
    {
        // Updating the asteroids, collision checking, etc
        ...
        M.update(gameTime);
        R.update(gameTime);
    }
    base.Update(gameTime);
    

    Will be run inside the first foreach loop. You are updating the player, the background, every asteroid, and the window once for each mob, every time you call update. This is only meant to happen once per update, not once per mob that is being updated. This is why your gaming is lagging or freezing. This is just a misplacement of the bracket on the mob's foreach loop - shift all this stuff outside the foreach loop.

    The other thing wrong is this part:

    foreach (Roids R in asteroidList)
    {
        // Updating the asteroids, collision checking, etc
        ...
        M.update(gameTime); /* THIS LINE HERE */
        R.update(gameTime);
    }
    

    Here, you are updating each Mob member once per asteroid. If you have 15 asteroids on screen, each mob member will be updated 15 times. Shift that line up into the first foreach loop.