Godot button size defined by texture size?

Godot Version

4.2.1

Question

I’m trying to create a button. I would like the button to be 120x120. The button is a child of a control node that has a size of 120x120. I have a texture that is 1024x1024. when I apply it to the button the button grows to 1024x1024. Is this normal?

Here is the C# code:

`using Godot;
using System;

public partial class ControlButton : Control
{
	[Export]
	public string ButtonUpTexture { get; set; } = "res://Assets/Textures/RedX.png";
	[Export]
	public string ButtonDownTexture { get; set; } = "res://Assets/Textures/RedX_down.png";
	[Export]
	public Vector2 ButtonPosition { get; set; } = new Vector2(0, 0);
	[Export]
	public Vector2 ButtonSize { get; set; } = new Vector2(100, 100);
	[Export]
	public string ButtonSignal { get; set; } = "NotDefined";

	private Action<object, string> buttonPressedCallback;

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		MakeButton();
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
	}

	public void SetButtonPressedCallback(Action<object, string> callback)
	{
		buttonPressedCallback = callback;
	}

	private void MakeButton()
	{
		Control controlNode = new Control();
		AddChild(controlNode);

		// Set the button's position, size, or any other properties as needed
		controlNode.Position = ButtonPosition;
		controlNode.Size = ButtonSize;  // Set the rect_min_size property for size

		TouchScreenButton buttonNode = new TouchScreenButton();

		// Load the PNG file and set it as the button texture
		var textureUp = GD.Load<Texture2D>(ButtonUpTexture);
		var textureDown = GD.Load<Texture2D>(ButtonDownTexture);

		buttonNode.TextureNormal = textureUp;
		buttonNode.TexturePressed = textureDown;

		controlNode.AddChild(buttonNode);

		// Connect the Pressed signal to the _OnButtonPressed method
		buttonNode.Pressed += _OnButtonPressed;
	}

	private void _OnButtonPressed()
	{
		// Handle button press
		GD.Print("Button Pressed!");

		// Invoke the Action
		buttonPressedCallback?.Invoke(this, ButtonSignal);
	}
}

You could set custom_minium_size of button to (120,120) and expand_icon to true, then the texture you assign to your button will be automatically resized to that size

EDIT: I did not realise you were extending Control class and not just using Button class

Mixing Controls and Node2Ds is not recommended as they won’t inherit correctly the transform.

In your case you’ll need to scale down the TouchScreenButton

1 Like

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