paul1
January 10, 2025, 10:11am
1
Godot Version
4.3
Question
Okay, I’m back with a hopefully easy problem.
I spawn a world object (characterbody2d) and I want it to appear ALWAYS at the same place on the screen. Not the same place in the world but on the screen of the player. No matter the zoom or movement of the camera ( I have one camera2d for the player).
How do I do this? It is not a control node so the simple canvas solution does not work. How do I know what coordinates, for example, off the right upper corner of my screen at this moment?
Thx for your help and patience.
You can use this:
extends Node2D
func _ready():
var canvas_transform = get_viewport().get_canvas_transform()
var screen_top_left = -canvas_transform.origin
print(screen_top_left)
It is worth reading about canvas transforms but it is initially quite confusing TBH.
2 Likes
wchc
January 10, 2025, 11:01am
3
You can use Camera2D.get_canvas_transform().affine_inverse()
and multiply it by the screen position you want your node to be spawned in.
extends Node2D
@export var sprite: PackedScene
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("click"):
var instance: Node2D = sprite.instantiate() as Node2D
get_tree().current_scene.add_child(instance)
var screen_position_to_spawn: Vector2 = Vector2(get_viewport().size.x - 100, 100)
instance.global_position = get_viewport().get_camera_2d().get_canvas_transform().affine_inverse() * screen_position_to_spawn
You can see in my demo, the sprite is always spawned in the upper right corner as defined by the screen_position_to_spawn
variable.
3 Likes
Is your Camera2D node a child of your CharacterBody2D? If so you could move the Camera2D coordinates instead of your player ones and it will follow the movement of the player…
paul1
January 10, 2025, 11:31am
5
Okay WCHC that worked great. Now I have to sit down and understand all of THAT.
@ploped00 : No, it is a free camera. In this case there is no dedicated player character.
1 Like
paul1
January 10, 2025, 11:40am
6
If anybody is still watching I have a bonus question.
What is the best way to check if an area is empty (only objects that can collide with you) before spawning an object?
Is there a best practice?
If you want to get an overview of 2D coordinate systems, you can find infos in the documenation here:
For a deep dive into that topic, you can find infos here:
system
Closed
February 9, 2025, 11:51am
8
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.