Trying to move sprite towards mouseclick

Started by
4 comments, last by Flimflam 11 years, 1 month ago

Hello.

I'm fairly new to xna/c# and i'm starting to get a grasp on the whole game mechanics.

But i'ev run into an issue.

I want my sprite to move across the screen to my desired destination.

I can almost get this to work.

what i have so far:

i click somewhere on the screen, the sprite moves towards the mouse position, BUT if i move the mouse before the sprite reaches it's location it will follow the mouse. when it reaches the location, it stops and i can move the mouse.

what i want:

click anywhere on screen, sprite moves towards position while i can freely move mouse around, even click a new position and the sprite goes to that position instead.

here is my code so far:


            MouseState mouseState = Mouse.GetState();                                 //get the current mouse state 
            mousePosition = new Vector2(mouseState.X, mouseState.Y);     //get the target (the mouse cursor) 
            direction = (Vector2)mousePosition - Position;     //get the direction from arrow to cursor 
            direction.Normalize();
            Vector2 target;
            if (mouseState.LeftButton == ButtonState.Released && oldState.LeftButton == ButtonState.Pressed)
            {
                target = mousePosition;
                move = true;
            }
            target = mousePosition;  //this is the line that causes issues, but i can't remove it either.
            if (Vector2.Distance(target, Position) > 3 && move.Equals(true))
            {
                Position += direction * 5;
            }
            else
            {
                move = false;
            }

            oldState = mouseState; // this reassigns the old state so that it is ready for next time
Advertisement

You need to define your target vector outside the scope of the function, so each time the function gets called, target doesn't get reset. Move your declaration of "target" to the same place you defined oldState, then remove the "target = mousePosition;" line.

Also, unrelated but in your distance checking code, you can replace "move.Equals(true)" with just "move".

Ahh, yeah, thanks! But, it still doesn't work :(

if i click somewhere the sprite keeps chasing the mouse untill it reaches the destination.

Change this line:

direction = (Vector2)mousePosition - Position; //get the direction from arrow to cursor

to this:

direction = target - Position; //get the direction from arrow to cursor

Aaah, yeah. Thanks! Works perfect! :D

Didn't think about the direction. Next, make it only move along the X axis, but i'll try and figure that out myself :P

The answer is in the spoiler tag if you feel so inclined:

[spoiler]

Replace

Position += direction * 5;

With

Position.X += direction.X * 5;

Or, if Position is a property:

Position += new Vector2(direction.X * 5, Position.Y);

[/spoiler]

This topic is closed to new replies.

Advertisement