Created
May 11, 2021 09:51
-
-
Save securas/2400b3fa1a31650a270618d1c8851ae6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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
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
This is a Camera2D that snaps into positions in a grid if its parent moves to a given cell.
Important to notice are:
line 8: setting the camera as "toplevel" to decouple its position from its parent
line 13: compute the position of the parent normalized and floored to the screen size (same as grid size)
lines 18-20: this function updates the camera position. It can also be used to call signals to activate objects (e.g. enemies) depending on the active grid cell.