How to change the size and position of a texture in code

Godot Version

4

Question

When I click on the button, the texture changes, but the button is not centered. The button works, but the position and size change with each texture change.

extends Node2D
var clic = 0


func _ready() -> void:
	$Labelcchet.text = "СЧЁТ: " + str(clic)


func _on_touch_screen_button_pressed() -> void:
	clic += 1
	print(clic)
	
	$Labelcchet.text = "СЧЁТ: " + str(clic)
	
	if clic == 21:
		$TouchScreenButton.texture_normal = load("res://newpict/normal1.png")
		$TouchScreenButton.texture_pressed = load("res://newpict/clic1.png")
		$Labellvl.text = "Уровень: " + str(1)
	elif clic == 51:
		$TouchScreenButton.texture_normal = load("res://newpict/normal2.png")
		$TouchScreenButton.texture_pressed = load("res://newpict/clic2.png")
		$Labellvl.text = "Уровень: " + str(2)
	elif clic == 101:
		$TouchScreenButton.texture_normal = load("res://newpict/normal 4 
norn.png")
		$TouchScreenButton.texture_pressed = load("res://newpict/clic4.png")
		$Labellvl.text = "Уровень: " + str(3)

Can you share a screenshot of how the button looks like with all these different textures?
And also how you set up the TouchScreenButton.

1 Like

If you have set the button to be centered it will stay centered. My guess is you think it is centered, and when the size changes it’s looking odd because it is not actually centered.

That happens when the textures aren’t the same size. There are two easy solutions:

  1. Make all the textures the same size in pixels.
  2. Give the button a minimum size that reflects the largest texture’s size, and it will not change size.
1 Like