Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Marc-Clemens Lange |
Hey,
I tried to make my first game in godot. I followed the Godot Documentary for the ‘first Game’ documentary. I then got this error:
" Invalid type in built-in function ‘rand_range’. Cannot convert argument 1 from Nil to float."
The error is in the last line of code of the main file. I hope someone can help!
Have a nice day!
Here the main file:
extends Node
export (PackedScene) var Mob
var score
func _ready():
randomize()
func new_game():
score = 0
$Player.start($StartPosition.position)
$StartTimer.start()
$HUD.show_message("Get Ready")
$HUD.update_score(score)
func game_over():
$ScoreTimer.stop()
$MobTimer.stop()
$HUd.game_over()
func _on_StartTimer_timeout():
$MobTimer.start()
$ScoreTimer.start()
func _on_ScoreTimer_timeout():
score += 1
$HUD.update_score(score)
func _on_MobTimer_timeout():
$MobPath/MobSpawnLocation.set_offset(randi())
var mob = Mob.instance()
add_child(mob)
var direction = $MobPath/MobSpawnLocation.rotation
mob.position = $MobPath/MobSpawnLocation.position
direction += rand_range(-PI/4, PI/4)
mob.rotation = direction
mob.set_linear_velocity(Vector2(rand_range(mob.MIN_SPEED, mob.MAX_SPEED), 0).rotated(direction))
Here the Code for the Mobs:
extends RigidBody2D
export (int) var MIN_SPEED
export (int) var MAX_SPEED
var mob_types = ["fly", "swim", "walk"]
func _ready():
$AnimatedSprite.animation = mob_types[randi() % mob_types.size()]
func _on_VisibilityNotifier2D_screen_exited():
queue_free()
Here the code for the player:
extends Area2D
signal hit
export (int) var SPEED
var velocity = Vector2()
var screensize
func _ready():
hide()
screensize = get_viewport_rect().size
func _process(delta):
velocity = Vector2()
if Input.is_action_pressed("ui_right"):
velocity.x += 1
if Input.is_action_pressed("ui_left"):
velocity.x -= 1
if Input.is_action_pressed("ui_down"):
velocity.y += 1
if Input.is_action_pressed("ui_up"):
velocity.y -= 1
if velocity.length() > 0:
$AnimatedSprite.play()
velocity = velocity.normalized() * SPEED
else:
$AnimatedSprite.stop()
position += velocity * delta
position.x = clamp(position.x, 0, screensize.x)
position.y = clamp(position.y, 0, screensize.y)
if velocity.x != 0:
$AnimatedSprite.animation = "right"
$AnimatedSprite.flip_v = false
$AnimatedSprite.flip_h = velocity.x < 0
if velocity.y != 0:
$AnimatedSprite.animation = "up"
$AnimatedSprite.flip_v = velocity.y > 0
func _on_Player_body_entered(body):
hide()
emit_signal("hit")
call_deferred("set_monitoring", false)
func start(pos):
position = pos
show()
monitoring = true