Search code examples
c#xnacollisiongame-physics

How do I make the code Wait for a few milliseconds in C#?


I have made some collision if statements, but they didn't work.

        birdbox3.X += 5;
        birdbox3.Y -= 5;

        if (birdbox3.Intersects(Banner1)) {

            birdbox3.Y += 10;

        }
        else if (birdbox3.Intersects(Banner2)) { 

            birdbox3.Y = -birdbox3.Y; }

So if we take the first statement, the box is initially on the left down corner. According to my code, it would ideally be going right+up in my game, once it hits the banner on the extreme top, it should go down+right, thus both the X and the Y positions will increase. But what happens is that is starts bouncing really fast, after debugging I realised it was forever stuck in the first if, it's almost as if it collides 2 times, reverting Y to its initial movement, colliding a 3rd time, and doing the process over and over.

Which brings us to the question, how can I make the Update code run a tad bit slower, or after half a second or such passes, so when it runs, it doesn't misinterpret collisions? Thanks a lot!


Solution

  • If you look at your Update method definition (If you have a regular GameComponent or DrawableGameComponent) , you'll notice you have access to the GameTime:
    public override void Update(GameTime gameTime).

    You can use that variable to trigger the collision only after a set amount of time. To do that, surround everything by a big if which checks the time elapsed:

    private int elapsedTime = 0; //Declared at class level
    
    public override void Update(GameTime gameTime)
    {
        // We add the time spent since the last time Update was run
        elapsedTime += gameTime.ElapsedGameTime.TotalMilliseconds;
    
        if (elapsedTime > 500) // If last time is more than 500ms ago
        {
            elapsedTime = 0;
            birdbox3.X += 5;
            birdbox3.Y -= 5;
    
            if (birdbox3.Intersects(Banner1))
            {
                birdbox3.Y += 10;
            }
            else if (birdbox3.Intersects(Banner2))
            {
                birdbox3.Y = -birdbox3.Y;
            }
        }
    }
    

    In that case, the collision code is run only once every 500 milliseconds.

    We need to add the elapsed time each time Update is run. Then, when we exceed the threshold, we run the collision bit and reset the timer to 0.

    We need the local variable because ElapsedGameTime only knows how much time was spent since the last Update. To carry that number on multiple updates, we need to store it somewhere.


    I also encourage you to take a look at MSDN's Starter Kit: Platformer. You can find the download links at the bottom. There a lot of info that can be take from that, like effective screen/input management or a basic physics engine. In my opinion, it's the best thing from the official documentation.