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.