Get main camera up direction

Hi,

I’ve checked the shaderlab documentation and I haven’t found a way to get the main camera’s up direction in world space.

It is possible to get this information in a shader?

Thank you

edit: Sorry, I forgot to mention that I don’t want to do it by sending data to the shader thru a script.

You can just use Shader.SetGlobalVector(“_CameraUp”, Camera.main.transform.up) or use someMaterial.SetVector(“_CameraUp”, Camera.main.transform.up); Then add that variable to your shader.

In a surface shader it’s this… W being world, O being object, T being tangent space (if you’re using normal maps). Should be similar for a regular vert/frag shader.

struct Input {
	float3 cameraUpW;
	float3 cameraUpO;
	float3 cameraUpT;
};

float4x4 _CameraToWorld;

void vert (inout appdata_full v, out Input data)
{
	UNITY_INITIALIZE_OUTPUT(Input,v);
	data.cameraUpW = mul((float3x3)_CameraToWorld, float3(0,1,0));
	data.cameraUpO = mul((float3x3)_World2Object, data.cameraUpW);
	TANGENT_SPACE_ROTATION;
	data.cameraUpT = mul(rotation, data.cameraUpO);
}

Isn’t it also the third row of the UNITY_MATRIX_MV?

I didn’t know about _CameraToWorld.

Including “UnityCG.cginc” didn’t work.

I got it working by declaring it in my shader.

Thank you! :slight_smile:

Oh yeah I forgot that matrix defines the basis vectors for the camera.

Doesn’t it become the third column on OpenGL though?

I never really understood the row/column thing and whether it makes a cross-platform difference if you “abuse” matrices that way.

Camera right direction = UNITY_MATRIX_V[0].xyz = mul((float3x3)UNITY_MATRIX_V,float3(1,0,0));
Camera up direction = UNITY_MATRIX_V[1].xyz = mul((float3x3)UNITY_MATRIX_V,float3(0,1,0));
Camera forward direction = UNITY_MATRIX_V[2].xyz = mul((float3x3)UNITY_MATRIX_V,float3(0,0,1));
Camera position = _WorldSpaceCameraPos = mul(UNITY_MATRIX_V,float4(0,0,0,1)).xyz;

3 Likes

I ended up using UNITY_MATRIX_V[1].xyz since there’s no need for matrix multiplication and just in case _CameraToWorld stops working sometime in the future.

Thank you!:stuck_out_tongue: