use ghast_client::{Controls, TickContext, Vec3};
use crate::{Bot, Error};
struct ReleaseKeys(Option<Bot>);
impl Drop for ReleaseKeys {
fn drop(&mut self) {
if let Some(bot) = self.0.take() {
bot.act(|ctx| ctx.set_controls(Controls::NONE));
}
}
}
const STUCK_TICKS: u32 = 60;
#[derive(Debug, Clone, Copy, Default)]
struct Walk {
last: Option<Vec3>,
still: u32,
}
fn walk_step(
ctx: &mut TickContext<'_>,
w: &mut Walk,
goal: Vec3,
range: f64,
sprint: bool,
) -> bool {
let p = *ctx.pose();
let (dx, dz) = (goal.x - p.pos.x, goal.z - p.pos.z);
let d = (dx * dx + dz * dz).sqrt();
if d <= range {
ctx.set_controls(Controls::NONE);
return true;
}
let yaw = (-dx).atan2(dz).to_degrees() as f32;
ctx.set_aim(yaw, p.pitch);
let moved = w.last.map_or(1.0, |l| {
((p.pos.x - l.x).powi(2) + (p.pos.z - l.z).powi(2)).sqrt()
});
w.still = if moved < 0.01 { w.still + 1 } else { 0 };
w.last = Some(p.pos);
let jump = p.on_ground && w.still >= 2;
ctx.set_controls(Controls {
forward: true,
sprint: sprint && d > 3.0,
jump,
..Controls::NONE
});
false
}
impl Bot {
pub async fn walk_straight_to(&self, goal: Vec3, range: f64) -> Result<(), Error> {
let mark = self.mark();
let mut keys = ReleaseKeys(Some(self.clone()));
let mut w = Walk::default();
loop {
let (done, ww) = self
.with(move |ctx| {
let mut w = w;
let done = walk_step(ctx, &mut w, goal, range, true);
(done, w)
})
.await?;
w = ww;
if done {
keys.0 = None;
return Ok(());
}
if w.still > STUCK_TICKS {
return Err(Error::Stuck);
}
self.next_tick().await;
self.check(mark)?;
}
}
pub async fn follow(&self, id: i32, range: f64) -> Result<(), Error> {
let mark = self.mark();
let _keys = ReleaseKeys(Some(self.clone()));
let mut w = Walk::default();
loop {
let r = self
.with(move |ctx| -> Result<Walk, Error> {
let e = crate::find::entity_info(ctx, id).ok_or(Error::NoSuchEntity(id))?;
let mut w = w;
if walk_step(ctx, &mut w, e.pos, range, true) {
let (yaw, pitch) = crate::yaw_pitch(
ctx.eyes(ctx.pose()),
Vec3::new(e.pos.x, e.pos.y + 1.6, e.pos.z),
);
ctx.set_aim(yaw, pitch);
w = Walk::default();
}
Ok(w)
})
.await??;
w = r;
if w.still > STUCK_TICKS {
return Err(Error::Stuck);
}
self.next_tick().await;
self.check(mark)?;
}
}
pub fn set_controls(&self, controls: Controls) {
self.act(move |ctx| ctx.set_controls(controls));
}
}