I’m having an issue moving a sprite between 2 points.
You can see the behavior here:
The starting and ending points are accurate, however somehow the direction/distance are wrong, or my calculation adding to the current position is wrong.
public void MoveTo(Point dest)
{
_endPos = dest.ToVector2();
_startPos = Position.ToVector2();
_distance = Vector2.Distance(_startPos, _endPos);
_direction = Vector2.Normalize(_endPos - _startPos);
_moving = true;
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
if (_moving == true)
{
Position = (Position.ToVector2() + (_direction * Speed * _elapsed)).ToPoint();
if (Vector2.Distance(_startPos, Position.ToVector2()) >= _distance)
{
Position = _endPos.ToPoint();
_moving = false;
}
}
}
For reference, Speed = 50, _elapsed = .1f.
ALl I’m trying to do is smoothly move the sprite between the two points.
OK…
so, why does this take longer than 1 second to move? I’m telling update to update my location every 1/100 of a second. This takes like 3 seconds when I specify 1 as my “seconds” in my moveTo function.
Changing my post here… I saw that you are, in fact, using gameTime.ElapsedGameTime.TotalSeconds in your velocity calculations, but you’re doing something kind of weird with it.
I’m curious, why are you trying to fix your calculations to a fixed rate? Your game does just happen to run at 60 updates per second by default, but that may not always be the case as you might decide you want to change this, or things might start slowing down as you add more stuff to your game.
You should be able to simply calculate your velocity as (distance_to_travel / time_to_travel) * direction_to_travel, and then update your position position += velocity * gameTime.ElapsedGameTime.TotalSeconds.
If you’re worried about overshooting, you can always just calculate when a position change puts you past the point you wanted to reach and stop there. If you need to continue, calculate the time that is unconsumed from the previous move and add that time to the next move.
I mean, if I’ve misunderstood and you’re doing something very specific and intentional, no worries… it just looked a bit off to me and I wanted to check in that this is what you were looking to do