簡體   English   中英

C#-Monogame.Forms:有關獲取鼠標坐標的問題

[英]C# - Monogame.Forms: Question about getting mouse coordinates

移動相機時,在控件上獲得正確的鼠標位置時出現問題。 控制器的寬度為800px,高度為600px。

讓我們只看一下繪制方法:在這里,我唯一要做的就是從屏幕中心到鼠標位置畫一條線。 問題在於,當攝像機移動時,結果與攝像機在x:0,y:0位置時的結果不同。

protected override void Draw()
{
    GraphicsDevice.Clear(new Color(50, 50, 50));
    SpriteBatch.Begin(SpriteSortMode.Deferred,BlendState.AlphaBlend, null, null, null, null,
        Camera.GetTransformationMatrix());

    Map.Draw(SpriteBatch);
    //SelectionTool.Draw(SpriteBatch);

    if (isPanning)
    {
        var point = PointToClient(MousePosition);
        Vector2 mousePosition = new Vector2(point.X, point.Y);
        Console.WriteLine(mousePosition);

        DrawLine(SpriteBatch, Camera.CenterScreen, mousePosition, Color.White);
    }

    SpriteBatch.End();
}

因此,我使用Camera.GetTransformationMatrix()繪制了控件:

public Matrix GetTransformationMatrix()
{
     return Matrix.CreateScale(new Vector3(1, 1, 0)) *
         Matrix.CreateTranslation(new Vector3(-View.X, -View.Y, 0));
}

對於移動相機,我適用:

public void Move(Vector2 distance)
{
    View.X += (int)(distance.X * panSpeed);
    View.Y += (int)(distance.Y * panSpeed);
}

畫線方法:

public void DrawLine(SpriteBatch spriteBatch, Vector2 from, Vector2 to, Color color, int width = 1)
{
    Rectangle rect = new Rectangle((int)from.X, (int)from.Y, (int)(to - from).Length() + width, width);
    Vector2 vector = Vector2.Normalize(from - to);
    float angle = (float)Math.Acos(Vector2.Dot(vector, -Vector2.UnitX));
    Vector2 origin = Vector2.Zero;

    if (from.Y > to.Y)
         angle = MathHelper.TwoPi - angle;

    SpriteBatch.Draw(lineTexture, rect, null, color, angle, origin, SpriteEffects.None, 0);
}

結果:

相機未移動
相機已移至右側

我試圖反轉矩陣以及使用PointToClientPointToScreen但沒有成功。

一段時間后,我最終根據這篇文章開始工作( https://gamedev.stackexchange.com/questions/85836/how-do-i-get-the-mouse-coordinates-relative-to-my-whole-scene -with-monogame )我要做的就是將攝像頭位置添加到鼠標位置:(Camera.cs)

public Vector2 GetMouse(Vector2 mouse) 
{
    Vector2 outVect = new Vector2(Position.X + mouse.X, Position.Y + mouse.Y);

    return outVect;
}

然后...(繪制方法)

    if (isPanning)
    {
        Vector2 mousePosition = Camera.GetMouse(currMousePos);
        Console.WriteLine(mousePosition);                

        DrawLine(SpriteBatch, Camera.CenterScreen, mousePosition, Color.White);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM