float in Godot – Complete Guide

Welcome to a comprehensive exploration of the `float` class in Godot 4, a powerful engine for creating games with rich, interactive experiences. As we delve into the world of floating-point arithmetic within Godot, you’ll discover how it can have a profound impact on game development, affecting everything from character movement to scaling in-game items. Our goal is to unpack the complexity of the `float` data type, making it accessible and engaging so that whether you’re just starting out or are an experienced coder, you’ll find valuable insights and practical uses for floats in your own projects.

What is the float Class in Godot 4?

The `float` class in Godot 4 is a fundamental data type representing numbers that have a decimal point. It’s a 64-bit, double-precision floating-point number similar to a double in C++. Providing 14 decimal digits of precision, this class enables developers to work with a wide range of values, from very small to very large. The significance of floating-point numbers lies in their ability to represent fractions and numbers that exceed the limits of standard integer types.

What is it for?

In Godot 4, the `float` class is ubiquitous, used in various engine methods and properties. For instance, while Vector2 and Vector3 use 32-bit floats by default, Godot can utilize 64-bit doubles if compiled accordingly. The precision of floats is critical for realistic physics calculations, smooth animations, and virtually any feature that requires numerical accuracy.

Why Should I Learn About Floats?

Understanding floating-point numbers is key to grasping the nuances of game mechanics and physics. As games often involve complex mathematical computations, knowing how to use the `float` class effectively can greatly enhance the quality of your games. Furthermore, learning about floats helps you to debug numerical errors and optimize performance, making your code more robust and your games more reliable.

CTA Small Image

Basic Operations with Floats

First, let’s cover the basic arithmetic operations you can perform with `float` values in Godot. These operations are essential for handling game mechanics such as movement speed, scaling, and more.

var a = 5.0  # Declaring a float value
var b = 3.2

# Addition
var sum = a + b  # sum will be 8.2

# Subtraction
var difference = a - b  # difference will be 1.8

# Multiplication
var product = a * b  # product will be 16.0

# Division
var quotient = a / b  # quotient will be approximately 1.5625

# Modulus - returns the remainder of division
var remainder = a % b  # remainder will be approximately 1.8

Moving beyond basic arithmetic, it’s common in game development to adjust values gradually over time for things like fading in music or changing light intensity.

var volume = 0.0  # Initial volume at 0%

# Increase volume by 5% until it reaches 100%
while volume < 1.0:
    volume += 0.05
    print("Current volume: " + str(volume))  # Output volume level to the console

Working with Trigonometric Functions

Trigonometry is essential in game development, particularly for determining angles, rotations, and positions. Godot’s `float` class works seamlessly with trigonometric functions.

var angle = 45.0  # Angle in degrees

# Godot uses radians for trigonometric functions, so let's convert degrees to radians
var radians = deg2rad(angle)

# Sine
var sine = sin(radians)  # sine will be 0.70710678118

# Cosine
var cosine = cos(radians)  # cosine will be 0.70710678118

# Tangent
var tangent = tan(radians)  # tangent will be 1.0

Godot also provides inverse trigonometric functions, which can be vital for calculating angles based on positions.

var x = 3.0
var y = 4.0

# Calculate the angle based on x and y position
var angle_in_radians = atan2(y, x)
var angle_in_degrees = rad2deg(angle_in_radians)  # Converts radians to degrees

Floats in Vector Calculations

When dealing with 2D or 3D space, vectors are often used in conjunction with floats to represent points and directions. Here’s how you can use floats within vector operations:

# Vector2 and floats
var vec2 = Vector2(2.5, 3.5)
var float_value = 10.0

# Scale a vector by a float value
var scaled_vector2 = vec2 * float_value  # Results in Vector2(25, 35)

# Vector3 and floats
var vec3 = Vector3(1.5, 2.5, 3.5)
var float_value3 = 4.0

# Translate a vector by a float value
var translated_vector3 = vec3 + Vector3(float_value3, float_value3, float_value3)  # Results in Vector3(5.5, 6.5, 7.5)

Controlling Precision with Floats

At times, managing the precision of float variables is necessary, particularly to avoid issues with floating-point arithmetic when you need to compare floats or round them off.

# Comparing floats
var float1 = 0.1 + 0.2
var float2 = 0.3

# Direct comparison might not work due to precision
if abs(float1 - float2) < 0.00001:
    print("The floats are approximately equal.")

# Rounding floats
var result = 3.14159
print(round(result))  # Outputs: 3
print(round(result, 2))  # Outputs: 3.14

# Truncating floats - note that int casting does not 'round' but 'truncates'
var truncated_result = int(result)  # Outputs: 3

By understanding these basic operations with floats, you can write more effective and precise code for your Godot projects. Next, we’ll explore more complex examples that involve floats and how they integrate with other parts of the Godot engine.

As we further explore the float class in Godot, let’s tackle some game-specific examples that showcase the practicality of floats in development.

Animating a character’s position smoothly over time can require interpolation between points. This is often achieved using floats combined with the linear interpolation (lerp) function.

# Interpolating position with lerp
var start_position = Vector2(0, 0)
var end_position = Vector2(10, 10)
var progress = 0.0

while progress < 1.0:
    var current_position = start_position.linear_interpolate(end_position, progress)
    progress += 0.01  # Increase progress for the next frame
    print("Current Position: " + str(current_position))

Controlling game difficulty can involve floats to adjust parameters dynamically, such as the spawn rate of enemies.

# Adjusting spawn rate of enemies
var base_spawn_time = 5.0  # Base time in seconds
var difficulty_multiplier = 1.0  

# Reducing spawn time as difficulty increases
func adjust_difficulty(increase: bool):
    if increase:
        difficulty_multiplier *= 0.9  # 10% harder
        difficulty_multiplier *= 1.1  # 10% easier
    var new_spawn_time = base_spawn_time * difficulty_multiplier
    print("New Spawn Time: " + str(new_spawn_time))

# Call this function to adjust difficulty

In games, physics-based calculations often need floats for applying forces or gravity. Here’s an example of using a float to apply gravity to a character’s jump.

# Applying gravity to a character
var velocity = Vector3()
var gravity = -9.81  # Earth-like gravity in m/s^2

func _physics_process(delta):
    velocity.y += gravity * delta  # Adjust vertical velocity
    # Assuming other movement code is handled elsewhere

Camera manipulation, such as zooming, often involves floats. We can smoothly zoom in or out using interpolation.

# Camera zooming
var current_zoom = Vector2(1, 1)
var target_zoom = Vector2(2, 2) # Double the size
var zoom_speed = 0.1

func _process(delta):
    current_zoom = current_zoom.linear_interpolate(target_zoom, zoom_speed * delta)
    $Camera2D.zoom = current_zoom  # Assuming the camera node is named Camera2D

Well-timed actions, such as cooldowns for abilities or weapon fire rates, can involve floats to track time elapsed.

# Ability cooldown timer
var cooldown_time = 3.0 # 3 seconds cooldown
var time_since_ability = 0.0 

func _process(delta):
    if time_since_ability < cooldown_time:
        time_since_ability += delta
        time_since_ability = 0.0

func use_ability():
    print("Ability used!")

With these examples, you can see how floats not only determine the properties of objects and animations in Godot but are integral for the implementation of game logic. Whether it’s managing the speed of a character, the timing of events, or the physics of the game world, a solid understanding of floats and their operations is critical for any game developer using Godot 4.

Advancing further into the depths of the float class in Godot, we uncover more intricate uses that elevate our gameplay elements and mechanics. Let’s dive into additional scenarios and code snippets where floats become the heroes of our game development narrative.

Particle Systems: Creating a mesmerizing particle effect often requires fine-tuning properties such as emission rate, speed, and lifespan, all of which commonly involve floats.

# Configure a particle system's emission rate
var particle_emission_rate = 50.0
$Particles2D.emission_rate = particle_emission_rate

# Adjust particle speed over time
var min_speed = 20.0
var max_speed = 100.0
func _process(delta):
    var new_speed = rand_range(min_speed, max_speed)
    $Particles2D.initial_velocity = new_speed

Health System: Implementing health systems typically involves floats to accurately represent health points, especially if you want to include fractional damage.

# Character health
var max_health = 100.0
var current_health = max_health

# Apply damage
func take_damage(amount: float):
    current_health -= amount
    if current_health <= 0.0:

# Heal
func heal(amount: float):
    current_health += amount
    current_health = min(current_health, max_health)  # Clamping to max health

Manipulating Light and Shadows: To create dynamic lighting effects, you might fade lights in and out, which can be achieved smoothly with floats. Let’s look at a scenario where we change a light’s intensity or range using interpolation.

# Adjust light intensity
var light_intensity = 1.0  # Full intensity
var target_intensity = 0.5  # Dimmed light
var light_change_speed = 0.05

func _process(delta):
    light_intensity = lerp(light_intensity, target_intensity, light_change_speed * delta)
    $Light2D.energy = light_intensity

Moving to a different domain, let’s consider audio control, where we manage sound volume and pitch. These interactions require fine adjustments, ideally suited for float calculations.

# Adjusting audio volume
var audio_player = $AudioStreamPlayer
var max_volume_db = 0.0  # Decibels
var fade_out_speed = -0.1  # Negative for fading out

func _process(delta):
    if audio_player.volume_db > -80.0:  # Lower than -80dB is inaudible
        audio_player.volume_db += fade_out_speed * delta

Lastly, let’s dive into gameplay mechanics involving time and scoring, which benefit enormously from the precision offered by floats.

# Timer-based scoring system
var score = 0.0
var time_passed = 0.0
var scoring_rate = 10.0  # Points per second

func _process(delta):
    time_passed += delta
    score += scoring_rate * delta

# Encounter a scoring event
func scoring_event(points: float):
    score += points

In these examples, you can see how the float class extends its reach across various aspects of Godot game development. This showcases the undeniable importance of floats — from visual and audio effects to time-sensitive gameplay mechanics. Mastery over manipulating floats is not just beneficial, it’s imperative for the modern game developer looking to harness the full power of the Godot engine.

Continue Your Game Development Journey

With a newfound grasp of floating-point arithmetic in Godot 4, your game development journey is just getting started. We encourage you to keep building, experimenting, and expanding your knowledge. The Godot Game Development Mini-Degree is the next step forward. This extensive collection of courses is designed to take you deeper into the aspect of cross-platform game creation with Godot 4, covering a wide range of topics from 2D and 3D assets to various game mechanics.

At Zenva, we understand that learning is an ongoing adventure. Whether you’re a complete beginner or looking to sharpen your skills, our Godot courses provide you with the tools to succeed in the game development industry. Our content is crafted to be engaging and practical, ensuring you can learn at your own pace and on any modern device. Explore the abundance of opportunities that await by diving into our full range of Godot courses, and keep up the unstoppable momentum on your path to becoming a proficient game developer with Zenva.


In wrapping up our foray into the world of floating-point numbers in Godot 4, it’s clear that the float class is more than just a data type. It is, in fact, a cornerstone of many game development processes, from physics and animation to scoring and sound. Whether you’re polishing the subtle nuances of a character’s movement or orchestrating the perfect timing for a game event, mastering floats allows you to create richer, more responsive game experiences that resonate with players.

But don’t let the journey end here; consider this a mere glimpse into the realm of possibilities that Godot offers. We at Zenva are committed to your growth as a game developer, and our Godot Game Development Mini-Degree is tailored to equip you with the skills and knowledge to bring your creative visions to life. So leap into your next adventure with confidence, and let’s continue creating amazing games together!

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.