从xna / monogame中的鼠标拖动中获取第一个和最后一个点

时间:2017-07-23 02:32:22

标签: c# xna monogame

我有一个瓷砖网格,我希望能够像这样抓住一个区域:enter image description here

这是我目前的代码:

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;

现在它只是毛刺而且...行为很奇怪......很难解释,有时它会选择,其他人,它会选择错误的区域。 任何帮助都是折旧的!

1 个答案:

答案 0 :(得分:1)

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

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)和一个变量,指示我当前是否正在拖动。< / p>

我试图尽可能地优化它:

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

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

这也阻止我不止一次致电Mouse.GetState()

祝你好运。