Smooth multiplayer movement
I'm attempting to create smooth movement from the other players in my game, and although it's smooth, it gets rather behind when one walks for more than 5-10 seconds or so.
I know the issue: It's because that player's speed is X pixels per step and it can just get unaligned. I don't really know how to fix it, though. Right now, the dummy-player's drawing position moves towards the point at X speed it receives from the server. I've tried simply using the average开发者_开发问答 of the current and the old point to try and make it smooth, but that just results in jittery movement almost as bad as not doing anything at all.
It seems like my options are limited to either inaccurate positions due to getting behind or jittery movement. Do you know of any reliable methods to solve this issue? Thanks.
Here's the code for moving the draw position:
Vector2 sMove = new Vector2(Position.X - DrawPosition.X, Position.Y - DrawPosition.Y);
sMove.Normalize();
sMove = Vector2.Multiply(sMove, Math.Min(Vector2.Distance(DrawPosition, Position), Speed));
DrawPosition.X += sMove.X;
DrawPosition.Y += sMove.Y;
I suspect that you are running this game on two computers with different specs. Considering that your movement doesn't take into account the amount of time that has passed since the last update, the faster processor will likely execute this update more times per second, and therefore move further. To fix this, you should use time-based movement using a "delta time". XNA already provides this for you. Your code should look more like this:
protected override void Update(GameTime gameTime)
{
Vector2 sMove = new Vector2(Position.X - DrawPosition.X, Position.Y - DrawPosition.Y);
sMove.Normalize();
// START CHANGE
sMove = Vector2.Multiply(sMove, Math.Min(Vector2.Distance(DrawPosition, Position), Speed * gameTime.ElapsedGameTime.TotalSeconds));
// END CHANGE
DrawPosition.X += sMove.X;
DrawPosition.Y += sMove.Y;
}
Where your "Speed" variable (or constant), is now a Speed per second. When this is executed on different machines, the units will move at the same rate and I believe your problem will go away. I had the exact same problem a number of years ago.
Float operations are not deterministic, due to rounding or hardware differences, the best approah to this problem is using fixed point math.
http://paulbergeron.posterous.com/fixed-point-math-in-c
精彩评论