I'm trying to prevent the player from going out of view

Godot Version

Godot 4.6

Question

About three-ish days ago I started watching the first two videos of Brackeys’ tutorials, and today I felt ready enough to make a quick and simple game.

For it though, the player needs to be stopped from leaving the sides of the view. My thought process was to do something similar to what I did in a previous game engine which was to kind of just clamp the x position based on the size of the sprite and the room.

Here’s the code I wrote down:

@export var playerSprite : Sprite2D
@export var viewport : SubViewport

func _process(delta: float) -> void:
	position.x = clamp(position.x, playerSprite.scale.x / 2, 
		viewport.get_visible_rect().size.x - playerSprite.scale.x / 2)

(Originally I wasn’t going to use a viewport, but the more I looked into how to get the size of the “room” in Godot the more I realized that was the only option coming up.)

Whenever I test this, it would prevent the player from moving but not from leaving the view. Instead it only prevented the player from moving beyond the center of the of player’s view.

Why not just using Staticbody2D with collision shapes as the boundaries?

If you have a tilemap you can get the bounds of that. But I do agree with the above comment, if you’re using a physics body, physics are typically the easiest way to limit it.

There are infinite world boundary shapes that could be used so it doesn’t have to be a box shape, just edges.

Also scale.x is going to be likely a small value, since it’s use in multiplication for the size of items it renders. A collision shape would solve this also, but to correctly get the size of a sprite you’d want to get the texture size and multiply it by the scale of the sprite node.