Barycentric Hexagon

Creates a hexagon out of 6 triangles using barycentric coordinates.

Can rotate hexagon any amount.

Can turn off and on individual triangles.

Shader code
shader_type canvas_item;

uniform float rotation : hint_range(0.0, 360.0) = 0.0;

uniform float tri0 : hint_range(0.0, 1.0, 1.0) = 1.0;
uniform float tri1 : hint_range(0.0, 1.0, 1.0) = 1.0;
uniform float tri2 : hint_range(0.0, 1.0, 1.0) = 1.0;
uniform float tri3 : hint_range(0.0, 1.0, 1.0) = 1.0;
uniform float tri4 : hint_range(0.0, 1.0, 1.0) = 1.0;
uniform float tri5 : hint_range(0.0, 1.0, 1.0) = 1.0;

const vec2 ptC = vec2(0.,0.);
varying flat vec2 pt0;
varying flat vec2 pt1;
varying flat vec2 pt2;
varying flat vec2 pt3;
varying flat vec2 pt4;
varying flat vec2 pt5;

float pnt_in_tri(vec2 p, vec2 a, vec2 b, vec2 c) {
    float d = ((b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y));
    float u = ((b.y - c.y) * (p.x - c.x) + (c.x - b.x) * (p.y - c.y)) / d;
    float v = ((c.y - a.y) * (p.x - c.x) + (a.x - c.x) * (p.y - c.y)) / d;
    float w = 1.0 - u - v;
    return step(0.,u)*step(u,1.)*step(0.,v)*step(v,1.)*step(0.,w)*step(w,1.);
}

void vertex() {
	float rot = rotation * PI / 180.;
	pt0 = vec2(cos(rot),-sin(rot));
	pt1 = vec2(cos(rot+PI/3.),-sin(rot+PI/3.));
	pt2 = vec2(cos(rot+2.*PI/3.),-sin(rot+2.*PI/3.));
	pt3 = vec2(cos(rot+3.*PI/3.),-sin(rot+3.*PI/3.));
	pt4 = vec2(cos(rot+4.*PI/3.),-sin(rot+4.*PI/3.));
	pt5 = vec2(cos(rot+5.*PI/3.),-sin(rot+5.*PI/3.));
}

void fragment() {
	vec2 uv = UV * 2. - 1.;
	float hex =
		tri0 * pnt_in_tri(uv, ptC, pt0, pt1) +
		tri1 * pnt_in_tri(uv, ptC, pt1, pt2) +
		tri2 * pnt_in_tri(uv, ptC, pt2, pt3) +
		tri3 * pnt_in_tri(uv, ptC, pt3, pt4) +
		tri4 * pnt_in_tri(uv, ptC, pt4, pt5) +
		tri5 * pnt_in_tri(uv, ptC, pt5, pt0);
	COLOR = COLOR * hex;
}
Tags
Barycentric, hexagon, triangle
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from award

Tile UVs

Related shaders

Hexagon pattern

Hexagon Shield

Hexagon TileMap Fog of War

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments