简体   繁体   中英

How do I move a player to where my mouse is clicked in a game in C#/XNA?

I know how to get the ship to move with keyboard and gamepad at the moment, but I am trying to figure out how to also move it with the mouse (as in, when I click somewhere on the screen the player moves to that location). I have got the mouse to show within the game, but how do I get it to track it and accept the click, etc.?

You will need to translate the screen coordinates of the mouse cusror to in-world coordinates, then move the player to that in-world coordinate

The movement depends on your circumstances (the game), but the simplest case is

  1. calculate the vector connecting the player's current position and the desired new location,
  2. normalize the vector to a size that represents movement in a unit amount of time,
  3. then update the player's coordinates by the normalized vector until it reaches it s destination

Use something like this, Get the mouse state and get the coordinates from it. Then use the size of tiles in your game (if your player moves to tiles, otherwise ignore that)

 MouseState ms = Mouse.GetState();
    double x = Math.Floor(((double)ms.X  / (double)TILE WIDTH);
    double y = Math.Floor(((double)ms.Y  / (double)TILE HEIGHT);

        if (ms.RightButton == ButtonState.Pressed)
        {

            //Player.Position = new Vector2(x,y)... or something like that



        }
        if (ms.LeftButton == ButtonState.Pressed)
        {
            //And so on...



        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM