ShaderMaterial, Rotating 3D shapes around the y-axis and letting it bounce up and down.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Xian

I wanted to create a shadermaterial that bounces and rotate only the rendered image of the material. That way I can reduce the cpu usage of the game I am making. So far I manage to make it bounce and rotate but when rotating the image gets distorted or deformed. Here’s my code:

void vertex() {
	UV=UV*uv1_scale.xy+uv1_offset.xy;
	float rotate = mod(TIME,360.0);
	VERTEX.y += sin(TIME)*0.1;
	VERTEX.x = (VERTEX.x * cos(rotate)) - (VERTEX.z * sin(rotate));
	VERTEX.z = (VERTEX.z * cos(rotate)) + (VERTEX.x * sin(rotate));
} 

I was making use of the formula

x′=xcosθ−ysinθ
y′=ycosθ+xsinθ

Where my x is the x value of the vertex and the z is my y value. Making it look like this.

VERTEX.x = (VERTEX.x * cos(rotate)) - (VERTEX.z * sin(rotate));
VERTEX.z = (VERTEX.z * cos(rotate)) + (VERTEX.x * sin(rotate));

The degree it rotates around is made passively using the

float rotate = mod(TIME,360.0);

As for the y value of the vertex, I am using it to create the bouncing effect.

VERTEX.y += sin(TIME)*0.1

So far it works, but I can’t seem to figure out why the image distorts while rotating. Please help super senpais.

Hi,
first of all, i m pretty sure that glsl cos uses radiants and not euler degrees.

Can you post a screenshot of the distortion?

klaas | 2020-09-03 07:07

:bust_in_silhouette: Reply From: klaas

Hi,
nevermind the screenshot i rquested … ive tested it myself.
Im not totaly aware what causes the distortion. Maybe its some sort of gimbal lock effect when rotating around the pole.

But i would do something like this

vec2 rotate2D(vec2 v, float a) {
	float s = sin(a);
	float c = cos(a);
	mat2 m = mat2(vec2(c,-s),vec2(s,c));
	return m * v;
}

void vertex() {
	UV=UV*uv1_scale.xy+uv1_offset.xy;
	VERTEX.xz = rotate2D(VERTEX.xz,TIME);
}

since shaders are optimized for vector and matrix operations this should be realy fast.

Yup that fixed it thanks klaas senpai xD I think your right as well. It have really been gimbal lock that caused it the first time.

Xian | 2020-09-03 09:01