3D Rotation in 2D

This shader basically uses a 3D rotation matrix to simulate 3D rotation onto CanvasItems.

You can change the rotation using the sliders provided within it’s parameters.

You may choose if your parameters are in Degrees or Radians with a boolean.

Make sure you are changing the correct parameters when rotating!

 

In case it’s needed, it’s VisualShader Node version is in the Demo project link, feel free to use it aswell!

In the VisualShader Node edition, you will find an option to choose if your input is in Degrees or Radians.

(It is the one with .gd extension.)

Shader code
// Heyo! This shader tries to simulate a 3D rotation on CanvasItems. Feel free to change its code to your desired use!

shader_type canvas_item;

uniform bool isInRadians = false;

group_uniforms ShaderParameters.RadianRotation;
uniform float xRadians: hint_range(0, 6.2830); // X IS FIXED
uniform float yRadians: hint_range(0, 6.2830); // Y IS FIXED
uniform float zRadians: hint_range(0, 6.2830); // Z IS FIXED
group_uniforms;

group_uniforms ShaderParameters.DegreesRotation;
uniform float xDegrees: hint_range(0, 360); // X IS FIXED
uniform float yDegrees: hint_range(0, 360); // Y IS FIXED
uniform float zDegrees: hint_range(0, 360); // Z IS FIXED
group_uniforms;

float degToRad(float angle) {
	return angle * PI / 180.0;
}

void vertex() {
	float radX = xRadians;
	float radY = yRadians;
	float radZ = zRadians;
	
	if (!isInRadians) {
		radX = degToRad(xDegrees);
		radY = degToRad(yDegrees);
		radZ = degToRad(zDegrees);
	}
	
	float cosX = cos(radX);
	float cosY = cos(radY);
	float cosZ = cos(radZ);
	
	float sinX = sin(radX);
	float sinY = sin(radY);
	float sinZ = sin(radZ);
	
	mat3 finalRot;
	finalRot[0][0] = cosZ * cosY;
	finalRot[1][0] = cosZ * sinY * sinX - sinZ * cosX;
	finalRot[2][0] = sinZ * sinX + cosZ * sinY * cosX;
	
	finalRot[0][1] = sinZ * cosY;
	finalRot[1][1] = cosZ * cosX + sinZ * sinY * sinX;
	finalRot[2][1] = sinZ * sinY * cosX - cosZ * sinX;
	
	finalRot[0][2] = -sinY;
	finalRot[1][2] = cosY * sinX;
	finalRot[2][2] = cosY * cosX;
	
	vec3 pos = vec3(VERTEX.xy, 0) * finalRot;
	VERTEX = pos.xy;
}

void fragment() {
}
Tags
2d, 3d, perspective, rotation
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

RotSprite-Like Algorithm for Cleaner Pixel Art Rotation

2D Rotation deform

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
comaybay
comaybay
20 days ago

This is a godsend, thank you!