Random Car Color Help...

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By The Maker

I wrote some code for setting the hood of a car to a random color, but it is always white. please help me write code that will work.

extends Sprite

Declare member variables here. Examples:

var a = 2

var b = “text”

var option1 = preload(“res://car parts/Car Hood1.png”)
var option2 = preload(“res://car parts/Car Hood2.png”)
var option3 = preload(“res://car parts/Car Hood3.png”)
var option4 = preload(“res://car parts/Car Hood4.png”)
var option5 = preload(“res://car parts/Car Hood5.png”)
var option6 = preload(“res://car parts/Car Hood6.png”)
onready var me = get_node(“/root/Car/Car_Hood1”)
var ranum = rand_range(1,7)

Called when the node enters the scene tree for the first time.

func _ready():
if (ranum > 1) and (ranum<2):
if (ranum > 2) and (ranum<3):
if (ranum > 3) and (ranum<4):
if (ranum > 4) and (ranum<5):
if (ranum > 5) and (ranum<6):
if (ranum > 6) and (ranum<7):

Called every frame. ‘delta’ is the elapsed time since the previous frame.

#func _process(delta):


:bust_in_silhouette: Reply From: timothybrentwood
var ranum 
func ready():
    ranum = rand_range(1,7)

randomize() selects a new random seed for random number generation when you call it. Otherwise you’ll get the same seed every time, which is great for testing but not so great for game play.

:bust_in_silhouette: Reply From: Lola

your conditions (if ranum > x and ranum < x+1) will never be true since no interger can be between x and x+1. In your code, changing one of the < or > to <= or >= would do what you were trying to do, which would basically be the same as testing if ranum == x.

But your way of doing is overly complicated for the task acomplished. A much elegant solution would be using an array:

# create an array with all possible textures
var hoods = [
    preload("res://car parts/Car Hood 1.png"),
    preload("res://car parts/Car Hood 2.png"),

func _ready():
    var hood_index = rand_range(0, hoods.size()) # pick an option

This make it adapt to how many different hoods you have, the only requirement if you add or remove one being updating the hoods array.

Thank you SO much! I am a noob, I hope you understand. this helps a LOT with my game. again, thank you so much.

The Maker | 2021-09-02 15:14