ants/src/ant.rs

48 lines
1.4 KiB
Rust
Raw Normal View History

2021-10-06 00:56:06 +00:00
use crate::constants::ANT_SPEED;
use crate::constants::MAP_HEIGHT;
use crate::constants::MAP_WIDTH;
2021-10-03 20:23:57 +00:00
use crate::Drawable;
2021-10-03 19:49:30 +00:00
use macroquad::prelude::*;
2021-10-03 19:59:18 +00:00
use macroquad::rand::RandomRange;
2021-10-03 20:23:57 +00:00
use std::f32::consts::PI;
2021-10-03 19:49:30 +00:00
pub(crate) struct Ant {
2021-10-03 20:23:57 +00:00
pos: Vec2,
dir: f32,
2021-10-03 19:49:30 +00:00
}
impl Ant {
2021-10-03 20:23:57 +00:00
pub(crate) fn init(num: i32) -> Vec<Self> {
let dir_steps = PI * 2. / num as f32;
(0..num)
.into_iter()
.map(|n| Ant {
2021-10-06 00:56:06 +00:00
pos: Vec2::new((MAP_WIDTH / 2) as f32, (MAP_HEIGHT / 2) as f32),
2021-10-03 20:23:57 +00:00
dir: n as f32 * dir_steps,
})
.collect()
}
2021-10-06 00:56:06 +00:00
pub(crate) fn walk(&mut self, frame_time: f32, trail_map: &mut Image) {
2021-10-03 20:23:57 +00:00
let new_dir = PI / 8. * RandomRange::gen_range(-2, 2) as f32;
self.dir += new_dir;
2021-10-06 00:56:06 +00:00
if self.dir > 2. * PI {
self.dir -= 2. * PI;
}
2021-10-03 19:59:18 +00:00
2021-10-03 20:23:57 +00:00
let acceleration = Vec2::new(self.dir.sin(), -self.dir.cos());
2021-10-06 00:56:06 +00:00
self.pos += acceleration * ANT_SPEED * frame_time;
// TODO: this is not fixing out of bounds write
self.pos.x = self.pos.x.clamp(0., MAP_WIDTH as f32);
self.pos.y = self.pos.y.clamp(0., MAP_HEIGHT as f32);
// TODO: change color over time
trail_map.set_pixel(self.pos.x as u32, self.pos.y as u32, RED);
2021-10-03 19:49:30 +00:00
}
}
2021-10-03 20:23:57 +00:00
impl Drawable for Ant {
fn draw(&self) {
2021-10-06 00:56:06 +00:00
draw_circle(self.pos.x, self.pos.y, 1., WHITE);
2021-10-03 20:23:57 +00:00
}
}