I would like the player to move towards the mouse when the player right clicks. The player does move, but doesn't stop when the player reaches the point. Here is the code.

void playerUpdate(GameTime gameTime)
        float dT = (float)gameTime.ElapsedGameTime.TotalSeconds;
        player.pos.X += player.vel.X * dT;
        player.pos.Y += player.vel.Y * dT;

        player.checkDest(x2y2, player.pos);

        if ((mouse.RightButton == ButtonState.Pressed) && (player.moving == false))
            x2y2.X = mouse.X;
            x2y2.Y = mouse.Y;

            player.move(x2y2, player.pos);


The player's file,

        public void move(Vector2 dest, Vector2 pos)
        dist.X = pos.X - dest.X;
        dist.Y = pos.Y - dest.Y;

        vel.X -= dist.X;
        vel.Y -= dist.Y;

        moving = true;

    public void checkDest(Vector2 dest, Vector2 pos)
        if (pos == dest)
            vel.X = 0;
            vel.Y = 0;
            moving = false;

I assume it is because of the player's position and its use of decimals and the mouse position being integers. How could I work around that?


1 Answer 1


You could compare player's distance to the destination and if it's small enough, stop. So replace this line:

if (pos == dest)


if (Vector2.Distance( pos, dest ) < 0.1f) // Adjust the value if it's not good
  • 1
    \$\begingroup\$ Aditionally to 'stop' when close enough is to 'set' the object to the exact target position. Trivia: the 0.1 value is often referred to as epsilon, the greek symbol used to indicate the margin of error due to floatingpoint arithmic. So often you'll encounter code like "if (a<= epsilon)" where epsilon is defined as a constant. \$\endgroup\$
    – Felsir
    Sep 11, 2016 at 9:13
  • \$\begingroup\$ Thank you for this. I wasn't aware that there was a distance method. That really helps. \$\endgroup\$
    – user220631
    Sep 12, 2016 at 2:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .