0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ His olddelta stays the same until the difference reaches 5 \$\endgroup\$ – Bálint Jul 10 '18 at 4:24
  • \$\begingroup\$ @Bálint Yes, but he is comparing the delta between two timesteps, which wouldn't differ by 5 msecs, unless the machine stalls noticeably. newdelta should be incremented by delta instead of being assigned directly. \$\endgroup\$ – Bojidar Marinov Aug 11 '18 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.