XNA - Mouse coordinates to word space transformation

Posted by Gabriel Butcher on Stack Overflow See other posts from Stack Overflow or by Gabriel Butcher
Published on 2012-06-09T16:35:17Z Indexed on 2012/06/09 16:40 UTC
Read the original article Hit count: 271

Filed under:
|
|

I have a pretty annoying problem. I would like to create a drawing program, using winform + XNA combo.

The most important part would be to transform the mouse position into the XNA drawn grid - I was able to make it for the translations, but it only work if I don't zoom in - when I do, the coordinates simply went horrible wrong.

And I have no idea what I doing wrong. I tried to transform with scaling matrix, transform with inverse scaling matrix, multiplying with zoom, but none seems to work.

In the beginning (with zoom value = 1) the grid starts from (0,0,0) going to (Width, Height, 0). I was able to get coordinates based on this grid as long as the zoom value didn't changed at all. I using a custom shader, with orthographic projection matrix, identity view matrix, and the transformed world matrix.

Here is the two main method:

        internal void Update(RenderData data)
    {
        KeyboardState keyS = Keyboard.GetState();
        MouseState mouS = Mouse.GetState();

        if (ButtonState.Pressed == mouS.RightButton)
        {
            camTarget.X -= (float)(mouS.X - oldMstate.X) / 2;
            camTarget.Y += (float)(mouS.Y - oldMstate.Y) / 2;
        }

        if (ButtonState.Pressed == mouS.MiddleButton || keyS.IsKeyDown(Keys.Space))
        {
            zVal += (float)(mouS.Y - oldMstate.Y) / 10;

            zoom = (float)Math.Pow(2, zVal);
        }

        oldKState = keyS;
        oldMstate = mouS;

        world = Matrix.CreateTranslation(new Vector3(-camTarget.X, -camTarget.Y, 0)) * Matrix.CreateScale(zoom / 2);
    }

internal PointF MousePos
    {
        get
        {
            Vector2 mousePos = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);

            Matrix trans = Matrix.CreateTranslation(new Vector3(camTarget.X - (Width / 2), -camTarget.Y + (Height / 2), 0));

            mousePos = Vector2.Transform(mousePos, trans);

            return new PointF(mousePos.X, mousePos.Y);
        }
    }

The second method should return the coordinates of the mouse cursor based on the grid (where the (0,0) point of the grid is the top-left corner.).

But is just don't work. I deleted the zoom transformation from the matrix trans, as I didnt was able to get any useful result (most of the time, the coordinates was horrible wrong, mostly many thousand when the grid's size is 500x500).

Any idea, or suggestion? I trying to solve this simple problem for two days now :\

© Stack Overflow or respective owner

Related posts about c#

Related posts about XNA