Files
tgcc-artest/Scenes/camera_subpixel.gd
Matteo Sonaglioni f7b334b21c first commit
2026-03-10 23:54:57 +01:00

30 lines
1.1 KiB
GDScript

extends Camera3D
@export var pixel_art_resolution := Vector2(320, 180) # Change to your low-res viewport size
func _process(_delta: float) -> void:
if projection != Camera3D.PROJECTION_ORTHOGONAL:
push_warning("Camera snapping script requires Orthogonal projection!")
return
# 1. Reset offsets to 0 first so they don't compound from the last frame
h_offset = 0.0
v_offset = 0.0
# 2. Get the exact 2D screen position of the camera's 3D origin
var exact_screen_pos := unproject_position(global_position)
# 3. Find the nearest perfect integer pixel coordinate
var snapped_screen_pos := exact_screen_pos.round()
# 4. Calculate the sub-pixel difference (the floating-point remainder)
var subpixel_diff := exact_screen_pos - snapped_screen_pos
# 5. Convert 1 pixel into 3D world units based on your orthogonal size
var units_per_pixel: float = size / pixel_art_resolution.y
# 6. Counteract the movement by shifting the camera's rendering frustum
# (Y is inverted because Godot's 2D screen Y goes down, but 3D world Y goes up)
h_offset = subpixel_diff.x * units_per_pixel
v_offset = -subpixel_diff.y * units_per_pixel