So, I'm trying to make my sprite walk to the X-coordinate of my mouse click. This is my code:
currentMouseState = Mouse.GetState();
MouseState mouseState = Mouse.GetState();
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
int mouseposx = mouseState.X;
if (playerPosition.X < mouseposx)
{
playerPosition.X += 3;
}
if (playerPosition.X > mouseposx)
{
playerPosition.X -= 3;
}
}`
The problem is that the sprite will walk only 3 pixels and then stop. If I use while instead, like this:
currentMouseState = Mouse.GetState();
MouseState mouseState = Mouse.GetState();
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
int mouseposx = mouseState.X;
while (playerPosition.X < mouseposx)
{
playerPosition.X += 3;
}
while (playerPosition.X > mouseposx)
{
playerPosition.X -= 3;
}
}
it will simply teleport to the X-coordinate instead. I tried adding a delay using Thread.Sleep(ms), but that just made it freeze and then teleport anyway.
So, what should I do?
EDIT: This is the new code, by Byte56.
currentMouseState = Mouse.GetState();
MouseState mouseState = Mouse.GetState();
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
if (playerPosition.X - mouseState.X < 3)
{
playerPosition.X = mouseState.X;
}
else if (playerPosition.X < mouseState.X)
{
playerPosition.X += 3;
}
else if (playerPosition.X > mouseState.X)
{
playerPosition.X -= 3;
}
}
edit3:
void update()
{
// Check if the player has reached the target, if not, move towards it.
if (playerPosition.X - playerTarget.X < 3)
{
playerPosition.X = playerTarget.X;
}
else if (playerPosition.X > playerTarget.X)
{
playerPosition.X -= 3;
}
else if (playerPosition.X < playerTarget.X)
{
playerPosition.X += 3;
}
}
and
currentMouseState = Mouse.GetState();
MouseState mouseState = Mouse.GetState();
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
// This will give the player a target to go to.
playerTarget.X = mouseState.X;
}
update();