GDScript Random Tutorial – Complete Guide

Welcome to this in-depth tutorial on “GDScript Random”. We will guide you through the process of understanding, implementing and utilizing random functions effectively in your game development process with GDScript. If you want to give your games an element of unpredictability and excitement, then learning how to implement randomness is an essential step.

What is GDScript Random?

Randomness in GDScript refers to the set of functions provided by the language that allows you to generate random numbers. This could be from a given range or, for more advanced uses, a random distribution.

Why Should you learn it?

Learning how to implement randomness in GDScript can vastly increase the richness and dynamism of your games. It allows unpredictable behaviour which becomes intriguing and challenging to the players.

Furthermore, the concept of randomness is not limited to just game development. It is a widely used programming concept in different fields such as machine learning, data science, and even in web development. Hence, understanding it will be a value addition to your programming skills.

Let’s dive into some code!

GDScript’s Built-In Random Functions

GDScript offers a variety of built-in functions for generating random numbers.

# Generate a random float between 0 and 1
var a = randf()

# Generate a random integer between 0 and a given 'n'
var b = randi() % n

The ‘randf()’ function generates a random floating-point number between 0 and 1. The ‘randi()’ function, on the other hand, generates a random integer. When you use modulo ‘%n’, it provides an integer between 0 and n-1.

Generating Random Numbers within a Range

Generating a random number within a specific range allows you to have better control over the randomness in your games. Here’s how you can do it.

# Generate a random float between min and max
var a = rand_range(min, max)

In the above code, ‘rand_range(min, max)’ returns a random floating-point number between the values of min and max.

Adding Randomness in Game Mechanics

You can use these random number generating functions in various game mechanics. For instance, randomizing player stats, enemy spawn points, loot drop rates, and so on.

# Example of randomizing player stat
player_hp = rand_range(80, 100)

# Example of randomizing spawn point
spawn_point = Vector2(rand_range(0, screen_width), rand_range(0, screen_height))

Further Learning with Zenva

If you’re excited about creating games using GDScript, we highly recommend our Godot Game Development Mini-Degree. It provides a comprehensive learning pathway to mastering game development using GDScript and Godot.

At Zenva, we offer programming and game creation content suitable for learners just starting out and experienced coders alike. Apart from GDScript, our mini-degree also covers other essential areas of game development.

Conclusion

You have now learned what GDScript random is, why it’s valuable, and how you can apply it to your games. By infusing randomness into your games, you can add layers of unpredictability and excitement that bring games to life.

If you’re interested in bolstering your game development skills further, do consider checking out the Godot Game Development Mini-Degree by Zenva. We are here to support you in your coding journey and beyond!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Random Movement of Game Characters

Randomness can be used to create unpredictable movement for game characters. This can make the gameplay more exciting as players will need to adapt to a change in patterns.

# Assume that we have a <a class="wpil_keyword_link" href="https://gamedevacademy.org/2d-game-development/" target="_blank" rel="noopener" title="2D game" data-wpil-keyword-link="linked">2D game</a>. 
# 'speed' is the movement speed of the character. 

var speed = 200 
var movement = Vector2()

In this snippet, a character movement vector is declared. The character’s speed is set to 200 units. The next step involves applying randomization to the movement.

# Apply random directions for movement

movement.x = rand_range(-1, 1)
movement.y = rand_range(-1, 1)

Here, the ‘rand_range’ function generates values between -1 and 1 for both x and y directions. Thus creating a randomized movement in all 2D directions.

# To apply the movement in the game, it can be included inside the '_physics_process()' function

func _physics_process(delta):
  position += movement * speed * delta

The ‘_physics_process()’ function is a built-in Godot function that is called every physics frame. The character’s position is updated by adding the movement vector multiplied by speed and delta (time since the last frame).

Random Spawning of Enemies

Another crucial application of randomization in gaming is in enemy spawn points. This unpredictability keeps the players on their toes.

# Assume 'Enemy' is a pre-defined class or a scene of an enemy character 
# and we have a function to spawn enemies at random time intervals

var next_spawn_time = 0

func _physics_process(delta):
    next_spawn_time -= delta
    if next_spawn_time < 0:
        spawn_enemy()
        next_spawn_time = rand_range(min_spawn_time, max_spawn_time)

The ‘next_spawn_time’ value is decreased by delta in each physics frame. Once it becomes less than zero, an enemy is spawned and the next spawn time is set to a random value between ‘min_spawn_time’ and ‘max_spawn_time’.

func spawn_enemy():
    var enemy = Enemy.instance()
    enemy.position = Vector2(rand_range(0, screen_width), rand_range(0, screen_height))
    add_child(enemy)

The ‘spawn_enemy()’ function creates an instance of the enemy, sets it to a random position within the screen, and adds it as a child to the current node.

Random Item Drops

Random item drops are a staple in many games. They provide a sense of anticipation and surprise. GDScript’s random functions excel in these situations.

# Assume 'Item' is a predefined class or a scene
# Let's say an enemy drops an item when it is destroyed

func _on_Enemy_destroyed():
    if (randf() < drop_rate):
        drop_item()

In the code, when an enemy is destroyed, a random float between 0 and 1 is generated. If the number is less than a certain drop rate, an item is dropped.

func drop_item():
    var item = Item.instance()
    item.position = position
    get_parent().add_child(item)

The ‘drop_item()’ function creates an instance of the item at the location of the killed enemy and adds it to the game scene.

Random Values in AI Behavior

A great use of random values in game development is to introduce unpredictable AI behavior, which can keep player engagements high.

# Let's say we have an AI character that can either walk or run
# We can use a random value to decide the state of the AI

enum AIState { IDLE, WALK, RUN }

var state = AIState.IDLE

In the snippet above, we define AI states as an enum (IDLE,WALK,RUN). The initial state is set to IDLE.

# Inside the '_physics_process()' function, we can update the AI state
func _physics_process(delta):
  var r = randf()
  if r < 0.01:
      state = AIState.IDLE
  elif r < 0.7:
      state = AIState.WALK
  else:
      state = AIState.RUN

The ‘randf()’ function here generates a random number between 0 and 1. Depending on the value, it changes the state of the AI. Notice how different states have different probabilities, making them happen more or less often.

Random Initialization of Game World

Randomness can be used to generate an unpredictable game world, thereby creating a unique experience each time the game is started.

# Consider we are creating a tile-based game
# We can randomize the game world at the start

func _ready():
    var map = get_node("Map")
    for i in range(0, map.get_cell_size().x):
        for j in range(0, map.get_cell_size().y):
            map.set_cell_item(i, j, randi() % 4)

The function ‘_ready()’ is called when the node and all its children, if any, entered the scene tree. Here, we retrieve a ‘Map’, which is assumed to be a GridMap, and for each tile in map, we set a random type of item (0 to 3 with modulo operation).

Random Time-based Events

Random time-based events can be used to create unpredictability in gameplay. A simple example is to change the game’s environment or spawn a bonus item at random intervals.

# Assume we are developing a game where it rains randomly 
# We start with defining a Timer node 

var timer = Timer.new()

The Timer node will provide the functionality for timed events. We create a new Timer in the snippet above.

# Inside the '_ready' function, we set up the timer 
func _ready():
    timer.set_wait_time(rand_range(min_wait_time, max_wait_time))
    timer.set_one_shot(true)
    timer.connect("timeout", self, "on_timer_timeout")
    add_child(timer)
    timer.start()

Inside the ‘_ready()’ function, we first set a random wait time for the timer. This will be the interval before the rain starts. The timer is set to be a one-shot timer, meaning it will only ring once. Then we connect the timeout signal to a function, add the timer to the scene, and start the timer.

# The 'on_timer_timeout' function will be called when the timer rings
# It will make it rain and then reset the timer with a new random wait time

func on_timer_timeout():
    make_it_rain()
    timer.set_wait_time(rand_range(min_wait_time, max_wait_time))
    timer.start()

The function ‘make_it_rain()’ is assumed to create a rain effect in the game. After the rain, the timer is reset to a new random time interval. Then the timer is started again, waiting for the next ‘make it rain’ event.

Remember to replace ‘min_wait_time’ and ‘max_wait_time’ with the actual minimum and maximum times you want for the events to occur.

These were just a few examples of how randomness can be effectively used in game development to make your game more dynamic and engaging. Try experimenting with different applications of randomness to see what exciting features you can bring to your game!

Random Level Generation

One of the most exciting applications of randomness is in procedurally generating game levels. This is a complex concept, but let’s look at a very simplified version of it.

# Assume we're creating a <a class="wpil_keyword_link" href="https://gamedevacademy.org/how-to-build-a-complete-2d-platformer-in-unity/" target="_blank" rel="noopener" title="2D platformer" data-wpil-keyword-link="linked">2D platformer</a> game, 
# and we want to randomize the position of platforms

for i in range(10):
    var platform = Platform.instance() 
    platform.position = Vector2(i * 200, rand_range(0, screen_height))
    add_child(platform)

In the above code, we’re creating 10 platforms and positioning them at regular intervals along the x-axis. What’s random here is each platform’s y-coordinate, giving us a unique vertical position for each platform every time we run the game.

Random Character Creation

Randomness is also commonly used in character creation, especially in deciding distinct character traits.

# Let's randomly determine some character attributes
func create_character():
    var character = Character.new()
    character.speed = rand_range(min_speed, max_speed)
    character.strength = rand_range(min_strength, max_strength)
    character.intelligence = rand_range(min_intelligence, max_intelligence)
    return character

In this code snippet, we’re using the ‘rand_range’ function to define a range for different character attributes – speed, strength, and intelligence. Each time a new character is created, these attributes receive a randomized value within the specified ranges.

Random Elements in Puzzle Games

Let’s see an example of how to randomize the placement of puzzle pieces in a puzzle game.

# Assume puzzle pieces are arranged in a grid, 
# and we want to shuffle the positions of the puzzle pieces

var grid_size = 4
var pieces = []

func _ready():
    # Create an ordered list of pieces
    for i in range(grid_size):
        for j in range(grid_size):
            var piece_index = i * grid_size + j
            pieces.append(piece_index)

    # Randomly shuffle the pieces
    for i in range(pieces.size()):
        var swap_with_pos = randi() % pieces.size()
        var temp = pieces[i]
        pieces[i] = pieces[swap_with_pos]
        pieces[swap_with_pos] = temp

In the above example, we first create an ordered list of the puzzle pieces. Then, we use the Fisher-Yates shuffle algorithm to randomly swap elements in the list, thus effectively randomizing the puzzle pieces’ positions.

Randomized Quest Rewards

Random values can be used for rewarding players with random rewards after completing a quest.

# Assume 'Reward' is a predefined class or a scene
# and we have a list of potential rewards

var rewards = ["Gold", "Sword", "Potion"]

func give_random_reward():
    var reward_name = rewards[randi() % rewards.size()]
    var reward = Reward.new(reward_name)
    return reward

In the given code, we have a list of possible rewards. Once a quest is completed, a ‘give_random_reward()’ function is triggered, which selects and returns a random reward from the list.

As we’ve seen, GDScript’s random functions can greatly enhance the gameplay experience by introducing variability and unpredictability. These examples have been simple, but you could see how they could be extended into more complex scenarios. Interested in learning more and creating your own dynamic, exciting games? Join us at Zenva for comprehensive lessons that cover these concepts and more.

Explore More with Godot’s GDScript

Through this tutorial, you have ventured into the world of randomization in game development using GDScript. The techniques you’ve learned today can greatly enhance your game design process by adding unpredictability and joy of discovery to your games. But the journey doesn’t stop here.

We invite you to continue your learning journey with us at Zenva’s Godot Game Development Mini-Degree. This comprehensive program doesn’t just restrict you to GDScript, but you’ll dive into other crucial aspects of game development such as two-dimensional & three-dimensional assets, gameplay control flow, player and enemy combat, user interfaces and much more. You’ll gain a holistic understanding of creating complete, cross-platform games with one of the most potent game engines out there – Godot 4.

At Zenva, we are committed to providing a pathway in your coding journey, from beginner to professional, with a broad collection of Godot courses. No matter if you’re starting your first lines of code or already have a background, we offer over 250 courses to advance your career. Embark on this adventure, earn certificates of completion and create games that captivate your audience.

Conclusion

You’ve now mastered the exciting world of GDScript Random, an integral part of game development, breathing life into your game mechanics with a dash of unpredictability. From creating random variables for character creation to crafting a randomized game world, your journeys in game development will now offer deeper, more engaging experiences for players.

The journey, however, has just begun. Continued learning and practice define the growth of a game developer. To continue this exploration and delve deeper into the universe of game development, do consider our comprehensive Godot Game Development Mini-Degree. At Zenva, your growth is our success, and we stand alongside you in your coding journey.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

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