I need to move an entity to the mouse location after i rightclick
- by I.Hristov
Well I've read the related questions-answers but still cant find a way to move my champion to the mouse position after a right-button mouse-click.
I use this code at the top:
float speed = (float)1/3;
And this is in my void Update:
//check if right mouse button is clicked
if (mouse.RightButton == ButtonState.Released && previousButtonState == ButtonState.Pressed)
{
// gets the position of the mouse in mousePosition
mousePosition = new Vector2(mouse.X, mouse.Y);
//gets the current position of champion (the drawRectangle)
currentChampionPosition = new Vector2(drawRectangle.X, drawRectangle.Y);
// move champion to mouse position:
//handles the case when the mouse position is really close to current position
if (Math.Abs(currentChampionPosition.X - mousePosition.X) <= speed &&
Math.Abs(currentChampionPosition.Y - mousePosition.Y) <= speed)
{
drawRectangle.X = (int)mousePosition.X;
drawRectangle.Y = (int)mousePosition.Y;
}
else if (currentChampionPosition != mousePosition)
{
drawRectangle.X += (int)((mousePosition.X - currentChampionPosition.X) * speed);
drawRectangle.Y += (int)((mousePosition.Y - currentChampionPosition.Y) * speed);
}
}
previousButtonState = mouse.RightButton;
What that code does at the moment is on a click it brings the sprite 1/3 of the distance to the mouse but only once. How do I make it move consistently all the time? It seems I am not updating the sprite at all.
EDIT
I added the Vector2 as Nick said and with speed changed to 50 it should be OK. I tried it with if ButtonState.Pressed and it works while pressing the button. Thanks.
However I wanted it to start moving when single mouse clicked. It should be moving until reaches the mousePosition.
The Edit of Nick's post says to create another Vector2, But I already have the one called mousePosition. Not sure how to use another one.
//gets a Vector2 direction to move *by Nick Wilson
Vector2 direction = mousePosition - currentChampionPosition;
//make the direction vector a unit vector
direction.Normalize();
//multiply with speed (number of pixels)
direction *= speed;
// move champion to mouse position
if (currentChampionPosition != mousePosition)
{
drawRectangle.X += (int)(direction.X);
drawRectangle.Y += (int)(direction.Y);
}
}
previousButtonState = mouse.RightButton;