在Monogame中使用鼠标实现拖放

时间:2015-09-10 06:50:33

标签: c# xna monogame

我试图在我的测试应用中实现一些窗口,现在我试图让这些窗口能够被拖动。

检查那个很棒的插图,看看我尝试做什么,以及实际发生了什么: enter image description here

首先,我检查鼠标位置是否在窗口顶部,如果按住鼠标左键,请执行以下操作:

if (mouseOver && LastLeftPressed && MouseLeftPressed)
{
     onHoldClick(Events);
}

这是我尝试过的:

private static void onHold(object sender, EventArgs e)
{
    var LastMouse = mousePosition;
    mousePosition = Mouse.GetState().Position;
    var window = sender as Window;
    if (LastMouse != mousePosition)
    {
        var deltaX = mousePosition.X - LastMouse.X;
        var deltaY = mousePosition.Y - LastMouse.Y;
        window.Rectangle = new Rectangle(mousePosition.X - deltaX, mousePosition.Y - deltaY, Width, Height);
    }
}

有时结果非常奇怪,例如窗口跳转到随机位置,但通常结果如上图所示。当我点击“按住”并快速移动鼠标时,窗口将立即移动到鼠标位置。

我无法解决这个问题。

1 个答案:

答案 0 :(得分:0)

我会做那样的事......

类字段:

private object grabbedObject;
private Vector2 grabOffset;
private MouseState mouseState; // update each Update() call

当鼠标按下时:

Vector2 mousePosition = new Vector2(this.mouseState.X, this.mouseState.Y);
Vector2 objectPosition = Vector2.Zero;
this.grabbedObject = GetClickedObject(mousePosition, out objectPosition);
if (this.grabbedObject != null)
{
    this.grabOffset = new Vector2(
        mousePosition.X - objectPosition.X,
        mousePosition.Y - objectPosition.Y);
}

private object GetClickedObject(Vector2 pMousePosition, out Vector2 pObjectPosition)
{
    Object clickedObject = null;
    // search first object you clicked on and set to clickedObject  
    pObjectPosition = clickedObject == null ? Vector2.Zero : clickedObject.Position;

    return clickedObject;
}

当鼠标按下时:

if (this.grabbedObject != null)
{
    // process drop action

    this.grabbedObject == null;
    this.grabOffset = Vector2.Zero;
}

绘图时:

if (this.grabbedObject != null)
{
    Vector2 position = new Vector2(
        this.mouseState.X - this.grabOffset.X,
        this.mouseState.Y - this.grabOffset.Y);
    // and so on...
}