1
votes

How to setup World,View and Projection for 2D? [XNA 3.1,C#]

I'm trying to use shaders which requires

float4x4 World;
float4x4 View;
float4x4 Projection;

But I don't know how to setup them with 2D engine. I mean I don't really know what value should I pass for the correct Vertex Shader calculating with 2D.

Code:

efs[ObjShaders[i].ShaderID].effect.Parameters["World"].SetValue(Matrix.Identity);

efs[ObjShaders[i].ShaderID].effect.Parameters["View"].SetValue(Matrix.CreateLookAt(new Vector3(0, 0, 0), new Vector3(0, 0, 0), new Vector3(0, 0, 0)));

efs[ObjShaders[i].ShaderID].effect.Parameters["Projection"].SetValue(Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),aspectRatio,1.0f, 10.0f));

efs[ObjShaders[i].ShaderID].effect.Parameters["EyePos"].SetValue(new Vector3(0,0,0));

Shader part:

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
VertexShaderOutput output;

float4 worldPosition = mul(float4(input.Position), World);
float4 viewPosition = mul(worldPosition, View);
output.Position = mul(viewPosition, Projection);

output.texCoord = input.texCoord*100;
output.worldPos = worldPosition.xyz;

return output;
}

Problem: When I try to use this with VertexShader = compile vs_2_0 VertexShaderFunction(); it just doesn't show anything. but If I just use PixelShader it draws the texture,but it feels a bit buggy and misplaced.

1
It's a bit vague. Have you tried anything yet? Are you following any tutorial?Allov
Yes. I tried. I updated my question with my code. But no success with that. If I use the VertexShaderFunction with that, it doesn't draw anything for me.Beardminator

1 Answers

2
votes

First of all find any documents about world-view-projection matrices and read it. You will understand about this matrices and fix you code like that:

  1. Matrix.CreateLookAt creates a view matrix by 3 vectors: position, target and up. If you pass all of them as zero vectors - matrix will be zero too. Try to use (0, 0, 0) for position, (0, 0, 1) for target and (0, 1, 0) for up.

  2. For 2D you must not use Perspective projection. Use Matrix.CreateOrthographic or Matrix.CreatePerspectiveOffCenter (read about differences in docs). You can pass your resolution in parameters then you pixel will be equals one unit in your worldspace (Matrix.CreateOrthographic(800, 600, -1, 1).