I'm trying to pass my player position to a shader script. To test it I'm trying to change the color of my terrain based on the player position. The terrain and player nodes are siblings.

I'm not really sure where to attach the script that passes this variable. I tried adding this script to my terrain node:

extends VoxelTerrain

var _player_y_position

func _ready():
	pass
	

func _physics_process(delta):
	var material = self.get_material(0)
	material.set_shader_param("player_y_position", _player_y_position)
	var _spatial : Spatial = get_parent().get_node("CharacterAvatar/Spatial")
	_player_y_position = _spatial.global_transform.origin.y
	print(_player_y_position) #This prints the correct player y position

Then inside my shader code I have:

uniform int player_y_position;


void vertex() {
	UV=UV*uv1_scale.xy+uv1_offset.xy;
}

void fragment() {
	vec2 base_uv = UV;
	vec4 albedo_tex = texture(texture_albedo,base_uv);
	float test = float(player_y_position)/100.0;
	albedo_tex *= vec4(1.0, 1.0, test, 1.0);
	ALBEDO = albedo.rgb * albedo_tex.rgb;
	ALPHA = albedo.a * albedo_tex.a;
	METALLIC = metallic;
	ROUGHNESS = roughness;
	SPECULAR = specular;

The player's y position starts at 18 and moves up and down as I jump and fall. I created a test variable to change the color of the terrain as my player moves up and down, but the color does not change.

Are you sure you are getting the material you are getting in the code is the material with the shader?

One way you could visualize the data passed into the shader is to use the height as the color for the R, G, and B channels, which should give you a grayscale image where the intensity is the value. Like this:

void fragment() {
	vec2 base_uv = UV
	float test = float(player_y_position)/100.0
	ALBEDO = vec3(test, test, test)
}

That might help visually show what is going on in the shader. Looking at the code and shader though, I do not see anything right off that would be causing the issue, other than maybe dividing by 100 in the shader is making the number so small that its effect is not visible.

a year later