How would i get a random range that is outside the player viewport but in inside the map ?

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

I need to spawn an enemy that is outside of the player viewport but inside the map
The Map is my screen size witch is (Width = 1024 and Height =600)
The code i written spawn the enemy in the same location

extends Node2D


export(PackedScene) var Enemy_Scene: PackedScene = preload("res://Scenes/Enemy.tscn")


func _physics_process(delta):

  if Input.is_action_just_pressed("ui_accept"):
	 spawn()
	
	
func spawn():
  randomize()
  var screen_size = get_viewport().get_visible_rect().size
  var Enemy_Scene = Enemy_Scene.instance()
  var x = rand_range(screen_size.x, 1024)
  var y = rand_range(screen_size.y, 600)
  Enemy_Scene.position.x = x
  Enemy_Scene.position.y = y
  get_tree().current_scene.add_child(Enemy_Scene.instance())
:bust_in_silhouette: Reply From: devAS

Because in the following two lines…

  var x = rand_range(screen_size.x, 1024)
  var y = rand_range(screen_size.y, 600)

screen_size.x and screen_size.y have the values 1024 and 600 respectively.
So, the enemies are getting spawned at the edges of viewport and not in the non-visible part of map.
I haven’t executed the code myself but from what I think you are trying to do, that seems to be causing the problem(unexpected result).

Ok so how do i fix it

javrocks | 2021-12-09 13:20

rand_range gives you a value between the first parameter and the second. In this case you want a value between 0 (aka left/top) and the screen size (aka right/bottom):

var x = rand_range(0, screen_size.x)
var y = rand_range(0, screen_size.y)

Keep in mind that you should never hardcode resolutions or similar parameters, as it will inevitably differ on the users’ machines.

skysphr | 2021-12-09 17:14

It still repeatedly spawns in the same location at the top left

javrocks | 2021-12-09 23:09

You have to give a range somewhat like…

var x = rand_range(screen_size.x, screen_size.x + 100)
var y = rand_range(screen_size.y, screen_size.y + 100)

what this’ll basically do is generate a number which in pixel of viewport size is out of the viewport, so your enemies outside of viewport at a distance of + 100 pixels beyond the viewport limit. You can change that distance to suit your specific needs.

Also, this will spawn enemies beyond right and top edges of viewport. To spawn enemies to the left and bottom limits of viewport, something like…

var x_negative = rand_range(0, -100)
var y_negative = rand_range(0, -100)

…will have to be done. And then you can use these co-ordinates.

devAS | 2021-12-10 11:35

If that solved your problem, you can select my answer as best to help others(never a bad idea)

devAS | 2021-12-12 10:14