Skip to content

Instantly share code, notes, and snippets.

@securas
Created May 11, 2021 09:51
Show Gist options
  • Save securas/2400b3fa1a31650a270618d1c8851ae6 to your computer and use it in GitHub Desktop.
Save securas/2400b3fa1a31650a270618d1c8851ae6 to your computer and use it in GitHub Desktop.
extends Camera2D
const SCREEN_SIZE := Vector2( 320, 180 )
var cur_screen := Vector2( 0, 0 )
func _ready():
set_as_toplevel( true )
global_position = get_parent().global_position
_update_screen( cur_screen )
func _physics_process(delta):
var parent_screen : Vector2 = ( get_parent().global_position / SCREEN_SIZE ).floor()
if not parent_screen.is_equal_approx( cur_screen ):
_update_screen( parent_screen )
func _update_screen( new_screen : Vector2 ):
cur_screen = new_screen
global_position = cur_screen * SCREEN_SIZE + SCREEN_SIZE * 0.5
@vedarthjoshi
Copy link

btw in godot 4 instead of "set_as_toplevel( true )" idk why they added an extra "_"
so now its set_as_top_level( true ) lol

@securas
Copy link
Author

securas commented Nov 14, 2023

btw in godot 4 instead of "set_as_toplevel( true )" idk why they added an extra "_"
so now its set_as_top_level( true ) lol

Could also do top_level = true

@mhogle25
Copy link

using Godot;

public partial class TransitionCamera : Camera2D 
{
	private Vector2 ScreenSize => GetViewportRect().Size;
	
	private Vector2 current = new(0, 0);

	public override void _Ready()
	{
		this.TopLevel = true;
		this.GlobalPosition = GetParent<Node2D>().GlobalPosition;
		UpdateScreen(this.current);
	}

	public override void _PhysicsProcess(double delta)
	{
		Vector2 parentScreen = ( GetParent<Node2D>().GlobalPosition / this.ScreenSize ).Floor();
		if (!parentScreen.IsEqualApprox(this.current))
			UpdateScreen(parentScreen);
	}
	
	private void UpdateScreen(Vector2 newScreen) 
	{
		this.current = newScreen;
		this.GlobalPosition = current * this.ScreenSize + this.ScreenSize * 0.5f;
	}
}

Translation to C# for Godot 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment