How can i make a sprite bounce/ hit of the edge of screen?

Godot 4.2.1
This is my code so far:
extends Sprite2D

var speed = 300
var screensize
var pos
var velocity = Vector2(100, 50)

func _ready():
screensize = get_viewport_rect().size
pos = screensize / 2

func _process(delta):
if Input.is_action_pressed(“ui_right”) or Input.is_key_pressed(KEY_D):
position.x += speed * delta
if Input.is_action_pressed(“ui_left”) or Input.is_key_pressed(KEY_A):
position.x -= speed * delta
if Input.is_action_pressed(“ui_up”) or Input.is_key_pressed(KEY_W):
position.y -= speed * delta
if Input.is_action_pressed(“ui_down”) or Input.is_key_pressed(KEY_S):
position.y += speed * delta

Basically im making a 2d game where the player controls the movement of the sprite, e.g going left or right. However, after the sprite makes contact with the edge of the screen, it continues to go out of the screen and disapear. (if you dont understand feel free to use this code to get where my error is).

Im looking to see if there is anything i have to change or add within my code to stop the spirte from exiting/leaving the viewers screen!

The screen size (and aspect ration) changes all the time, so it’s not advisable for most games to rely on it. But if you were to take this route, a simple solution could be:

if position.x > screensize.x:
   position.x = screensize.x
if position.x < 0.:
   position.x = 0.
if position.y > screensize.y:
   position.y = screensize.y
if position.y < 0.:
   position.y = 0.

Please note that this code does NOT take moving the camera into account, and it will not work well if the player resizes the game window.

The best method to solve this problem is to base the player controlled around a node with collision and place boundaries. The CharacterBody2D is suitable for this situation. StaticBody2D can be used for the boundaries. There are serveral good tutorial on using CharacterBody2D for your player character.

Thank you so much for this, appreciate it!