Reputation: 1883
I unlimited the frames per second in my game by doing.
graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;
But now my sprite/player moves WAY faster then it did before. I don't know why it does this, and I am not sure how to fix it.
if (keyboard.IsKeyDown(Keys.W) || keyboard.IsKeyDown(Keys.Up))
{
position.Y -= spd;
}
if (keyboard.IsKeyDown(Keys.A) || keyboard.IsKeyDown(Keys.Left))
{
position.X -= spd;
}
if (keyboard.IsKeyDown(Keys.S) || keyboard.IsKeyDown(Keys.Down))
{
position.Y += spd;
}
if (keyboard.IsKeyDown(Keys.D) || keyboard.IsKeyDown(Keys.Right))
{
position.X += spd;
}
That is currently how I am getting the sprite to move. spd = 4
at the moment. It worked perfectly fine, but now it seems as if it is moving like 2000 times faster. Just taping one of the keys takes him off screen.
Any and all help will be appreciated.
Upvotes: 2
Views: 1707
Reputation: 1294
The game loop in XNA is based around update and draw. Fixed time step also refers to update, so by setting that to false, you are telling update to be called as often as possible. As your code is in the update function, its being called more than the default, fixed 60 times per second.
rather than just using spd, change it to
spd * (gameTime.ElapsedGameTime.Milliseconds / 16);
That will change it so that the spd is scaled by the elapsed time. The 16 is the number of milliseconds an update takes at 60 fps (approx) which is what your spd value is currently working at.
EDIT: For not part of Game.cs:
Have an update on the class you are interested in moving (Im going to call it Ship, but it could be anything you want)
class Ship
{
public void Update(GameTime gameTime)
{
...
position.Y += spd * (gameTime.ElapsedGameTime.Milliseconds / 16);
...
}
..
}
Then in the Game.cs file:
public override Update(GameTime gameTime)
{
myShip.Update(gameTime);
...
}
myShip being the variable for the class of the sprite you want to move. Note update is no longer overriding a base method, so the call to base.Update is also gone
Upvotes: 4
Reputation: 44316
When you turn off a fixed timestep, you need to take the time delta into the calculation to have any control over movement. For example:
if (keyboard.IsKeyDown(Keys.W) || keyboard.IsKeyDown(Keys.Up))
{
position.Y -= spd * gameTime.ElapsedGameTime.TotalSeconds;
}
...
In this case, you would set spd
to the distance per second, not per frame.
Upvotes: 4