Unexpected result when using the “clamp” function

Godot Version

Godot v4.2.2 stable

Question

hello! I’m new in godot,

i’m practicing the basic functions of 2D games, i have a problem when i clamp to avoid the character to leave the viewport area.

the character doesn’t finish traversing the drawn tilemap before stopping completely.

my characterbody2d script

extends CharacterBody2D

const SPEED = 100
# @onready var player = $".."
@onready var animation = $AnimatedSprite2D

	

func _physics_process(delta):
	move_player(delta)
	position = position.clamp(Vector2.ZERO, get_viewport_rect().size)
	
	
func move_player(delta):
	
	velocity = Vector2(Input.get_axis("move_left","move_right"), 
	Input.get_axis("move_up", "move_down"))
	
	velocity = velocity.normalized() * SPEED 
	
	
	if Input.is_action_pressed("move_left"):
		animation.play("move_left")
		
	elif Input.is_action_pressed("move_right"):
		animation.play("move_right")
		
	elif Input.is_action_pressed("move_up"):
		animation.play("move_up")
		
	elif Input.is_action_pressed("move_down"):
		animation.play("move_down")
		
	else :
		animation.stop()
	
	move_and_slide()

data that may be useful

  • the viewport size of the project is 580x340
  • the tilemap is based on 16x16 textures
  • the character AnimatedSprites are 48x48 (scaled to 0.5)

Check for any offset or scaled nodes, see if Main or Player have a position other than zero.

2 Likes

Thank you for replying!

the only node that is offset is the player that I placed by hand in a specific position of the tilemap in the main tree. but in running time his position is = (0,0)
Is that the way to create the character on the map?

debugging i can observe that with few movements the character reaches the x or y position limit,

is it something to do with the size difference between the character (48x48) and the tilemap textures (16x16) ?

The Player offset might be it, the issue is your CharacterBody2D’s position is altered by the scripts but the Player node is it’s parent so any offset will affect the clamp. Try making the CharacterBody2D the root of that scene instead of a Node2D to make placement easier without having to use “editable children” in the main scene.

1 Like

now it works! thanks!!! it seems that the problem was that the parent node was a node2d and not the CharacterBody2D itself.

that’s weird
Thanks my dude!

It depends on where your script is. Since you were placing the Node2D but the script is a child of Node2D the CharacterBody2D (scripted) will think it’s at 0,0

Generally good to have your root node hold the most important script in a scene, “other node” will become the most used out of those initial options.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.