Help with x and y positions

Godot 4.2

So I’m making a simple game and I made it so that the Character moves to random positions, And I need help with understanding y and x positions since I made “Barriers” to keep the character from randomly moving off the screen and I DO NOT know the exact number of x and y position so my “Barrier” right now is set at 300x and 700 y but I want it to be within the space of the 9.031 x scale and the 5.633 y scale, So I need to translate the scale to a y and x position if anyone can help please do!

This depends on a lot of stuff. The camera position, the camera zoom, the resolution of your screen, the size of your character…

But if you only want to limit your player position so he doesn’t go off the screen, you can have a good approach with this code here. Assuming the camera zoom is 1.

extends CharacterBody2D

const SPEED = 500

var camera
@onready var sprite_2d = $Sprite2D

func _ready():
	camera = get_parent().get_node("Camera2D")

func _physics_process(delta):
	position.x += Input.get_axis("ui_left", "ui_right") * SPEED * delta
	position.y += Input.get_axis("ui_up", "ui_down") * SPEED * delta
	
	position = limit_character_position(position)

func limit_character_position(pos):
	#taking into account the visible size of the character
	var character_half_width = sprite_2d.get_rect().size.x / 2
	var character_half_height = sprite_2d.get_rect().size.x / 2
	
	#taking into account the camera position and the screen resolution
	var min_x = camera.position.x - get_viewport_rect().size.x / 2 + character_half_width
	var max_x = camera.position.x + get_viewport_rect().size.x / 2 - character_half_width
	var min_y = camera.position.y - get_viewport_rect().size.y / 2 + character_half_height
	var max_y = camera.position.y + get_viewport_rect().size.y / 2 - character_half_height

	pos.x = clamp(pos.x, min_x, max_x)
	pos.y = clamp(pos.y, min_y, max_y)
	
	return pos

And you don’t need to add barriers or anything, you limit the position by code.
Here’s the result, it works even changing the screen resolution.

This is the setup, as you can see, I didn’t need barriers. Just the player and a reference to the camera, the rest is all math.

image

By the way, you set up the screen resolution on your project settings, under Display->Window.

Thanks I’ll try it

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.