asteroids-genetic/src/asteroids.rs

87 lines
2.3 KiB
Rust
Raw Normal View History

2022-10-08 13:15:07 +00:00
use macroquad::{prelude::*, rand::gen_range};
2022-10-08 19:47:47 +00:00
pub enum AsteroidSize {
Large,
Medium,
Small,
}
2022-10-08 13:15:07 +00:00
pub struct Asteroid {
2022-10-08 15:27:05 +00:00
pub pos: Vec2,
2022-10-08 13:15:07 +00:00
vel: Vec2,
2022-10-08 19:47:47 +00:00
size: AsteroidSize,
2022-10-08 13:15:07 +00:00
sides: u8,
radius: f32,
rot: f32,
omega: f32,
2022-10-08 19:47:47 +00:00
pub alive: bool,
2022-10-08 13:15:07 +00:00
}
impl Asteroid {
2022-10-08 19:47:47 +00:00
pub fn new(size: AsteroidSize) -> Self {
let (sides, radius) = match size {
AsteroidSize::Large => (gen_range(6, 10), gen_range(40., 50.)),
AsteroidSize::Medium => (gen_range(5, 6), gen_range(20., 30.)),
AsteroidSize::Small => (gen_range(3, 5), gen_range(12., 18.)),
};
2022-10-08 13:15:07 +00:00
let mut r = vec2(
if gen_range(0., 1.) > 0.5 { -1. } else { 1. },
gen_range(-1., 1.),
);
if gen_range(0., 1.) > 0.5 {
r = vec2(r.y, r.x);
}
2022-10-08 15:27:05 +00:00
r *= vec2(
screen_width() * 0.5 + radius,
screen_height() * 0.5 + radius,
);
2022-10-08 13:15:07 +00:00
Self {
pos: r,
2022-10-08 19:47:47 +00:00
vel: 0.1 * -r
2022-10-08 15:27:05 +00:00
+ vec2(
gen_range(20., 60.) * if gen_range(0., 1.) > 0.5 { -1. } else { 1. },
gen_range(20., 60.) * if gen_range(0., 1.) > 0.5 { -1. } else { 1. },
),
2022-10-08 19:47:47 +00:00
size: size,
sides: sides,
2022-10-08 15:27:05 +00:00
radius: radius,
2022-10-08 13:15:07 +00:00
omega: gen_range(50., 200.) * if gen_range(0., 1.) > 0.5 { -1. } else { 1. },
2022-10-08 19:47:47 +00:00
rot: 0.,
alive: true,
2022-10-08 13:15:07 +00:00
}
}
2022-10-08 19:47:47 +00:00
pub fn check_collision(&mut self, pos: Vec2) -> bool {
let collided = (pos.x - self.pos.x) * (pos.x - self.pos.x)
+ (pos.y - self.pos.y) * (pos.y - self.pos.y)
<= self.radius * self.radius;
if collided {
self.alive = false;
}
return collided;
2022-10-08 13:15:07 +00:00
}
2022-10-08 19:47:47 +00:00
pub fn update(&mut self) {
if self.alive {
self.pos += self.vel * get_frame_time();
self.rot += self.omega * get_frame_time();
self.alive = self.pos.y.abs() < screen_height() * 0.51 + self.radius
&& self.pos.x.abs() < screen_width() * 0.51 + self.radius;
}
2022-10-08 15:27:05 +00:00
}
2022-10-08 19:47:47 +00:00
// pub fn is_visible(&self) -> bool {
// }
2022-10-08 13:15:07 +00:00
pub fn draw(&self) {
draw_poly_lines(
self.pos.x,
self.pos.y,
self.sides,
self.radius,
self.rot,
2.,
WHITE,
);
}
}