0 votes

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 = getnode("/root/Car/CarHood1")
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):
me.set
texture(option1)
if (ranum > 2) and (ranum<3):
me.settexture(option2)
if (ranum > 3) and (ranum<4):
me.set
texture(option3)
if (ranum > 4) and (ranum<5):
me.settexture(option4)
if (ranum > 5) and (ranum<6):
me.set
texture(option5)
if (ranum > 6) and (ranum<7):
me.set_texture(option6)

Called every frame. 'delta' is the elapsed time since the previous frame.

func _process(delta):

pass

Godot version 3.3.2
in Engine by (15 points)

2 Answers

+1 vote
Best answer

Hello,
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():
    randomize()
    var hood_index = rand_range(0, hoods.size()) # pick an option
    me.set_texture(hoods[hood_index])

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.

by (728 points)
selected by

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

0 votes
var ranum 
func ready():
    randomize()
    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.

by (3,389 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.