Height Extention when node active

Godot Version


so i’m learning how to spawn new nodes and change how they are interacting with each other based on how many nodes there are active

i got this:

extends StaticBody2D

var win_height : int
var p_height : int
var phB : int #botarm height
var phT : int #toparm height
var isBactive : bool = true #botarm active
var isTactive : bool = true #toparm active

# Called when the node enters the scene tree for the first time.
func _ready():
	#takes the size of the viewport and use y to get the height
	win_height = get_viewport_rect().size.y
	#takes the size of the ColorRect and use y to get the height
	p_height = $ColorRect.get_size().y #main paddle height
	phB = $botarm/ColorRect.get_size().y #get botarm height
	phT = $toparm/ColorRect.get_size().y #get toparm height

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	if Input.is_action_pressed("ui_up"):
		position.y -= get_parent().PADDLE_SPEED * delta
	elif Input.is_action_pressed("ui_down"):
		position.y += get_parent().PADDLE_SPEED * delta	
	#clamp the paddle to the screen
	if isBactive == true and isTactive == true:
		position.y = clamp(position.y, (p_height  + phB + phT)/2 , win_height - (p_height  + phB + phT)/2) 
	elif isBactive == true and isTactive == false:
		position.y = clamp(position.y, (p_height + phB) , win_height - (p_height + phB))
	elif isTactive == true:
		position.y = clamp(position.y, (p_height + phT)/2 , win_height - (p_height + phT)/2)
		position.y = clamp(position.y, p_height/2 , win_height - p_height/2)

and i would asume everything should work, but clamp does not work as i would expect when there is only one node active and the border for movement is like so:


i believe if you just want to clamp the paddle inside a box, you just need to spawn another staticbody2d in your board scene surrounding the play area. there’s no need to calculate the clamp position like this
utilize the godot collision physics

1 Like

Ok i used the tip @zdrmlpzdrmlp gave me but found out later what the problem was and maybe someone in the future will find it helpfull so …

I made the paddles children of the main paddle - so their position was counted as a relative to their parent node. Instead i should have used global position as a reference. That way the code worked fine and clamp worked fine.