0
\$\begingroup\$

Ive been rattling my head trying to figure out how to do this. I am not working on a 3D application so I did not expect to need to understand transforms, projections, or viewports.

Essentially what I want to do is to setup my viewport, view, & projection so that whenever I call GraphicsDevice.DrawPrimatives() the values of the VertexPosition's position can be pixel values. For example, If I wanted to draw a rectangle that bordered the screen I would do:

VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1920, 1080, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1920, 0, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(0, 1080, 0), Color.Red);

As of right now, if i do:

VertexPositionColor[] vertices = new VertexPositionColor[5];
vertices[0] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);
vertices[1] = new VertexPositionColor(new Vector3(1, 1, 0), Color.Red);
vertices[2] = new VertexPositionColor(new Vector3(1, -1, 0), Color.Red);
vertices[3] = new VertexPositionColor(new Vector3(-1, -1, 0), Color.Red);
vertices[4] = new VertexPositionColor(new Vector3(-1, 1, 0), Color.Red);

I get:

enter image description here

How do I set it up so that my VertexPosition coordinates are 1:1 with pixels?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

To do this, you need to set the correct projection value in your BasicEffect. Key to this projection is to align the matrix with the coordinate system you want to use (so 0,0 is the top left corner). Set it up like this:

        basicEffect = new BasicEffect(GraphicsDevice);
        basicEffect.VertexColorEnabled = true;
        basicEffect.Projection = Matrix.CreateOrthographicOffCenter
        (0, Screen.Width,     // left, right
        Screen.Height, 0,    // bottom, top
        0, 1);

In your case for a 1920x1080 display:

        basicEffect.Projection = Matrix.CreateOrthographicOffCenter
        (0, 1920,     // left, right
        1080, 0,    // bottom, top
        0, 1);

Now you can set your vertice coordinates to 0,0 (top left) and 1920,1080 (bottom right). This lines exactly up with the regular spriteBatch settings so you can mix those vertex graphics with sprites, using the same coordinate system.

Keep in mind that the projection "screen" values need to be the same with the backbuffer size (this is the reason I set the projection with values that correspond to the actual window size instead of magic numbers).

\$\endgroup\$
1
  • \$\begingroup\$ Thanks! thats exactly the explanation I was looking for. \$\endgroup\$
    – Dylan
    Dec 19, 2018 at 18:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .