When the game starts, I am trying to generate an object in a random area. It's working, but sometimes the object spawns in the players view.
How to have an object that generates in a random location, but not in the player's view?
You can use the function rectangle_in_rectangle to check if the bounding box of the object is inside the bounding box of the camera.
place_object_at_random_position()
var cameraLeft = bview_xview[0]
var cameraTop = view_yview[0]
var cameraRight = view_xview[0] + view_wview[0]
var cameraBottom = view_yview[0] + view_hview[0]
while (rectangle_in_rectangle(bbox_left, bbox_top, bbox_right, bbox_bottom,
cameraLeft, cameraTop, cameraRight, cameraBottom)) {
place_object_at_random_position()
}
If you for some reason cannot access the object's bounding box (bbox_left etc.) you can use point_in_rectangle instead.
var x = random_range(min, max)
var y = random_range(min, max)
var cameraLeft = bview_xview[0]
var cameraTop = view_yview[0]
var cameraRight = view_xview[0] + view_wview[0]
var cameraBottom = view_yview[0] + view_hview[0]
while (point_in_rectangle(x, y, cameraLeft, cameraTop, cameraRight, cameraBottom)) {
x = random_range(min, max)
y = random_range(min, max)
}
create_object_at(x, y)
The functions place_object_at_random_position and create_object_at are functions you define yourself.