在 xna/monogame 中通过鼠标拖动获取第一个和最后一个点

Take first and last point from mouse drag in xna/monogame

我有一个瓷砖网格,我希望能够像这样抓取一个区域:

这是我当前的代码:

case clickState.select:

    if (IsActive && //Check if window is active and mouse is within working area
        Mouse.GetState().X > 0 &&
        Mouse.GetState().X < windowSize.X - 32 &&
        Mouse.GetState().Y > 0 &&
        Mouse.GetState().Y < windowSize.Y - 32)
    {
        if (Mouse.GetState().LeftButton != ButtonState.Pressed && prevMouseState)//if has released, and last frame it wasnt:
        {
            Vector2 Topos = toTilePos(new Vector2(Mouse.GetState().X, Mouse.GetState().Y)); //convert the onscreen postion to coordinates on the grid
            selected.Z = Topos.X;  //yes i am using a vector4 to store 2 vector2s
            selected.W = Topos.Y;  //Z =x2, W = y2
            break;
        }
        if (Mouse.GetState().LeftButton == ButtonState.Pressed && !prevMouseState) //If started to click:
        {
            if (selected != new Vector4(0)) selected = new Vector4(0);  //Reset selected area
            prevMouseState = true; //The previouse state will be updated
            Vector2 Topos = toTilePos(new Vector2(Mouse.GetState().X, Mouse.GetState().Y)); //convert to tile space
            selected.X = Topos.X; // set
            selected.Y = Topos.Y; // set
            break;
       }
   }
   else if (prevMouseState == true)
       prevMouseState = false;
   break;

现在它只是出现故障并且...行为很奇怪..很难解释,有时它是 select,其他时候,它是 select 错误的区域。 感谢任何帮助!

我尝试创建我之前写过无数次的逻辑:

MouseState mouseState = Mouse.GetState();
if (mouseState.LeftButton == ButtonState.Pressed)
{
    end = new Vector2(mouseState.X, mouseState.Y);

    if (prevMouseState.LeftButton == ButtonState.Released)
    {
        start = end;
        selecting = true;
    }
}
else
    selecting = false;

prevMouseState = mouseState;

这是我获取两个点的更新逻辑(在我的例子中,两个 Vector2 称为 startend)和一个指示我当前是否正在拖拽的变量.

我尽力优化它:

只要我按下鼠标 1,我就会在每次更新调用时得到一个位置。当我第一次按下 Mouse1 时,我将新生成的位置分配给起始位置并保留它(在您的情况下为 Vector4)。 selecting 可以是任何东西,从布尔值到触发的事件。这只是一个例子,可以扩展。

我保留对从鼠标获得的最后信息的引用,并在我的代码底部更新它。

它还阻止我多次调用 Mouse.GetState()

祝你好运。