How to make black hole effect in 2D?

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

Good evening, forum users
How to make a black hole effect in 2D
I tried to use the Zylann effect, but I didn’t understand something

Do you mean graphical or physics cause if your question is physics I know what to do

Merlin1846 | 2020-02-02 19:46

In General, graphically, but I would not refuse a physical explanation

SDW | 2020-02-03 06:03

:bust_in_silhouette: Reply From: njamster

By “Zylann effect” you’re referring to this repository? It hasn’t been updated since 2017, so (depending on your Godot-version) it most likely won’t work as is.

So here’s a guide to port it over to Godot 3.2:

  1. Create a new scene, choose TextureRect as a root-node, name it “Background”
  2. Set it’s texture-property to any background image you want (e.g. platformer.jpg)
  3. Add a ColorRect as a child node of $Background, name it “BlackHole”
  4. Create a new shader material for $BlackHole (in the inspector under CanvasItem > Material > Material (Click The Dropdown) > New Shader Material)
  5. Create a new shader for $BlackHole (in the inspector under CanvasItem > Material > Shader (Click The Dropdown) > New Shader)
  6. Add the following code to for the shader:
shader_type canvas_item;

uniform float strength = 0.01;
uniform float black_radius = 0.65;

void fragment() {
	// Get direction and distance to the black hole center
	vec2 diff = vec2(0.5, 0.5) - vec2(UV.x, 1.0-UV.y);
	float d = length(diff) * 2.0;
	vec2 dir = normalize(diff);
	float f = clamp(1.0-d, 0.0, 1.0);
	
	// This is a 0..1 value that will nullify the effect around the bounds of the effect,
	// for a seamless transition between the effect's area and the unaffected world pixels.
	float shelf = smoothstep(0, 1, f);
	// Calculate displacement amount
	float displacement = strength / (d*d + 0.01);
	
	// Calculate distorted screen-space texture coordinates
	vec2 uv = SCREEN_UV + dir * (displacement * shelf);
	
	// Output pixels from the screen using distorted UVs
	vec3 col = texture(SCREEN_TEXTURE, uv).xyz;
	COLOR.rgb = mix(col, vec3(0,0,0), smoothstep(black_radius-0.01, black_radius+0.01, f));
}
  1. Finally, make sure $BlackHole is positioned somewhere inside the area covered by $Background. Resize it, to change the extent of the black hole effect.

Thank you…really

SDW | 2020-02-03 17:42