TransWikia.com

How to make object move in exact gametime in Monogame, XNA?

Game Development Asked by Steyrix on March 11, 2021

I have recently started learning monogame. The big question i faced is how to make object move, when gametime variable has an exact value.

//Update method in Game.cs
     float delta = (float)gameTime.ElapsedGameTime.Milliseconds / 1000f;
        if (CurrentState != null)
            CurrentState.update(delta);


     if (Keyboard.GetState().IsKeyDown(Keys.Enter))
            SetState(new GameState());

    //GameState.cs, there is a box that's need to be moved in 5 seconds
    Vector2 boxpos = new Vector2(800, Game1.graphics.PreferredBackBufferHeight / 2 - 100);
    float olddelta = 0;
    public void update(float delta)
    {
        float newdelta = delta;
        if (newdelta - olddelta >= 5)
        {
            boxpos += new Vector2(0, -200);
            olddelta = newdelta;
        }
    }

I’ve drawn a box in my gamestate’s draw method using spritebatch.Draw(Box, boxpos, null, Color.White, 0f, Vector2.Zero, 1f, SpriteEffects.None, 1f);, but it’s position remains constant.
I really have no idea how to do it in a right way. Hope can receive some help.

One Answer

Have you tried to step through your program, I suspect that your clause of >= 5 is never being met here. As you are taking in a frame in milliseconds, and taking away the previous frame, this value will remain very low. What you should be using here is an accumulation of time, so to reach that five second mark.

For a good reference on the subject, have a read of the following http://gafferongames.com/game-physics/fix-your-timestep/ It goes through the steps on implementing a time step correctly, and the reasoning behind it in a clear manner

Answered by David McGrane on March 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP