+1 vote

(One Screen Game)

I want that if the Game is Started that Player and Enemy spawn in different positions on the screen every time and Move Randomly every time (they will bounce of the screen and not frantic)

Please with Script i am big noob :/ big dream game

in Engine by (136 points)

2 Answers

+2 votes
Best answer

In player and enemy attach script and set this code into _ready() so it looks like this:

func _ready():
    var x_range = Vector2(100, 400)
    var y_range = Vector2(100, 400)

    var random_x = randi() % int(x_range[1]- x_range[0]) + 1 + x_range[0] 
    var random_y =  randi() % int(y_range[1]-y_range[0]) + 1 + y_range[0]
    var random_pos = Vector2(random_x, random_y)


This will make the x position be between 100 and 400 and the y position be between 100 and 400

by (254 points)
selected by
+1 vote

Every time you think of something "right when it started" you can use the ready function

func _ready():
    ##code here will run once on load

To pseudo randomize something, you will need to call for the randomize function once on the beginning of the level scene or project, you can also use the ready function for that. This will make sure that any random number generator function you use will use a different random seed every time this is called.


Now to generate randomness... there are many many ways.... but I'll give it a shot. Since what you want is positions (vector2 x y), you will need 2 values and whose values will have to be inside the viewport/camera region

randf() ## will give you a float value from 0 to 0.999999999.... (as far as I know it is never 1 unless its rounded)

randi() % 20 ## will give you an integer between 1 and 19 if I'm not mistaken

and you can round values with "round()"

so assuming your game level is 100x100, on the ready function I'd call

onready var player = $pathtoplayernode
onready var enemy = $pathtoenemynode

func _ready():
    player.global_position = vector2(randi() % 101, randi() % 101)
    player.speed = randi() % max_speed
    enemy.global_position = vector2(randi() % 101, randi() % 101)
    enemy.speed = randi() % max_speed

Should get you started, assuming you already have code to move them

by (363 points)

the idendifier "max_speed" is not declared

how do i declare max_function?

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.