Use clamp on [Node2D.position]https://docs.godotengine.org/en/stable/classes/class_node2d.html#class-node2d-property-position.
extends KinematicBody2Dconst GRAVITY = 200.0const WALK_SPEED = 200const JUMP_SPEED = 100var screen_sizevar velocity = Vector2()# Called when the node enters the scene tree for the first time.func _ready(): screen_size = get_viewport_rect().sizefunc _physics_process(delta): # gravity velocity.y += delta * GRAVITY # left and right movement if Input.is_action_pressed("ui_left"): velocity.x = -WALK_SPEED elif Input.is_action_pressed("ui_right"): velocity.x = WALK_SPEED else: velocity.x = 0 # jump if Input.is_action_pressed("ui_up"): velocity.y -= JUMP_SPEED # move current node move_and_slide(velocity, Vector2(0, -1)) # prevent movement exceed screen position.x = clamp(position.x, 0, screen_size.x) position.y = clamp(position.y, 0, screen_size.y)