Right, so in my Player class where I call the object I got an if statement which gets the coordinates for the mouse
bool PickedCoords = true;
MouseState mouseState = Mouse.GetState();
if (newState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released)
{
PickedCoords = true;
int MouseX = mouseState.X;
int MouseY = mouseState.Y;
}
else
{
PickedCoords = false;
}
oldState = newState; // this reassigns the old state so that it is ready for next time
Now how would I make MouseX and MouseY be used as the direction of the vector of my object moving in the specified X and Y coordinates? What I'm, almost trying to do is move the object in the direction of the mouse click and make it continue to move in that direction until it's stopped by whatever.
Answer
First you must subtract the the two position vectors, like so:
The Object I use here is just an example as I did not see any in your code snippet.
Vector2 Difference = Vector2.Subtract(Object.Position,new Vector2(MouseX,MouseY));
This will give you the vector pointing from the object's position to the mouse's position with the actual distance between the two.
After that, as Steven mentioned in the comments you can normalize this vector to get a standard direction vector.
Vector2 Direction = Vector2.Normalize(Difference);
This will return a standard 1 length direction vector that you can use with a velocity or speed variable to move the Object.
eg.
Object.Position += Direction * Velocity;
If you want the object to keep moving in the direction, you just don't change the Direction and Velocity, unless a collision or something else happens with the object.
I hope this helps your problem. :)
No comments:
Post a Comment