How do I use clamping for a KinematicBody in a _physics_process() function?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AdrianB
    extends KinematicBody2D

export (int) var speed = 200
var screen_size
var initial_pos_y = 100
func _ready():
	screen_size = get_viewport_rect().size

func _physics_process(delta):
	var velocity = Vector2()
	if Input.is_action_pressed("move_up"):
		velocity.y -= 1
	if Input.is_action_pressed("move_left"):
		velocity.x -= 1
	if Input.is_action_pressed("move_right"):
		velocity.x += 1
	if Input.is_action_pressed("move_down"):
		velocity.y += 1
	if velocity.length() > 0:
		velocity = velocity.normalized() * speed
	position += velocity * delta
	position.x += clamp(position.x,0,screen_size.x)
	position.y += clamp(position.y,0,screen_size.y)
	if velocity.x != 0:
		$AnimatedSprite.animation = "moving"
		$AnimatedSprite.flip_h = false
		$AnimatedSprite.flip_h = velocity.x < 0
		$AnimatedSprite.animation = "default"

//So ,this is the problem.Clamping won’t work…

:bust_in_silhouette: Reply From: godot_dev_

You may want to elaborate more (what are you trying to achieve, what is going wrong), but my first guess is you should use = instead of += when assigning the position using clamp. If the position is already off the scree (you appear to want to bound the position to within the screen), then your clamp logic won’t bring the position back onto the screen. So for example: trying doing

position.x = clamp(position.x,0,screen_size.x)
position.y = clamp(position.y,0,screen_size.y)

This will force the position to be within the screen bounds I believe

I want a simple movement for a kinematic body.I have,indeed, addressed the problem as you’ve shown me , although previously I had sent my failed attempt in resolving the issue,yet I still don’t have the expected result.The character goes beyond its’ boundaries…

AdrianB | 2023-04-29 22:10

It might be a relative position issue. Maybe using global_position instead of position could solve the problem. If that fails, you could create walls to prevent the kinematic body from moving beyond the walls, and place the walls where there boundaries are

godot_dev_ | 2023-05-02 15:10