Created
August 25, 2024 05:22
-
-
Save laundmo/1a49ce8b8dde958c273c3adee0cd8722 to your computer and use it in GitHub Desktop.
generate random points outside the screen bevy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use bevy::prelude::*; | |
use rand::{thread_rng, Rng}; | |
fn main() { | |
App::new() | |
.insert_resource(ClearColor(Color::srgb(1.0, 0.0, 0.0))) | |
.add_plugins(DefaultPlugins) | |
.add_systems(Startup, setup) | |
.add_systems(Update, point_out) | |
.run(); | |
} | |
fn setup(mut commands: Commands) { | |
commands.spawn(Camera2dBundle::default()); | |
} | |
fn rand_outside(rect: Rect) -> Vec2 { | |
let r = rect.inflate(100.0); // we want to be solidly outside the screen, not just on the edge | |
let Vec2 { | |
x: width, | |
y: height, | |
} = r.size(); | |
let perimeter = 2.0 * (width + height); | |
let rnum = rand::thread_rng().gen_range(0.0..perimeter); | |
if rnum < width { | |
// Bottom edge | |
Vec2 { | |
x: r.min.x + rnum, | |
y: r.min.y, | |
} | |
} else if rnum < width + height { | |
// Right edge | |
Vec2 { | |
x: r.max.x, | |
y: r.min.y + (rnum - width), | |
} | |
} else if rnum < 2.0 * width + height { | |
// Top edge | |
Vec2 { | |
x: r.max.x - (rnum - width - height), | |
y: r.max.y, | |
} | |
} else { | |
// Left edge | |
Vec2 { | |
x: r.min.x, | |
y: r.max.y - (rnum - 2.0 * width - height), | |
} | |
} | |
} | |
fn point_out( | |
mut gizmos: Gizmos, | |
q_window: Query<&Window>, | |
q_camera: Query<(&Camera, &GlobalTransform)>, | |
) { | |
let (camera, camera_transform) = q_camera.single(); | |
let window = q_window.single(); | |
let w = window.resolution.width(); | |
let h = window.resolution.height(); | |
let bottom_right = camera | |
.viewport_to_world_2d(camera_transform, Vec2::new(w, h)) | |
.unwrap(); | |
let top_left = camera | |
.viewport_to_world_2d(camera_transform, Vec2::new(0., 0.)) | |
.unwrap(); | |
let rect = Rect::from_corners(top_left, bottom_right); | |
let outside = rand_outside(rect); | |
gizmos.line_2d(Vec2::ZERO, outside, Color::WHITE); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment