rust-pilot/src/game/ship.rs

57 lines
1.5 KiB
Rust

use piston_window::math::*;
use std::f64::consts::*;
use std::f64::EPSILON;
use super::map::Map;
static TURN_RATE: Scalar = 4.0;
static THRUST_RATE: Scalar = 4.0;
const SHIP_POLY: &[[Scalar; 2]] = &[
[-10.0, -8.0],
[10.0, 0.0],
[-10.0, 8.0]
];
pub struct Ship {
pub rotation: Scalar,
pub position: Vec2d,
pub velocity: Vec2d,
pub geometry: &'static [[Scalar; 2]]
}
impl Ship {
pub fn new(loc: Vec2d) -> Self {
Ship {
rotation: -FRAC_PI_2,
position: loc,
velocity: [0.0, 0.0],
geometry: SHIP_POLY
}
}
pub fn update(&mut self, thr: Scalar, rot: Scalar, d_t: Scalar, map: &Map) {
let thrust = thr * THRUST_RATE * d_t;
let d_vel = [self.rotation.cos() * thrust, self.rotation.sin() * thrust];
let d_rot = rot * TURN_RATE * d_t;
self.rotation += d_rot;
self.velocity = add(self.velocity, d_vel);
self.position = add(self.position, self.velocity);
let oldpos = self.position;
self.position = map.clamp(oldpos);
if (self.position[0] - oldpos[0]).abs() >= EPSILON { self.velocity[0] = 0.0; }
if (self.position[1] - oldpos[1]).abs() >= EPSILON { self.velocity[1] = 0.0; }
}
pub fn trajectory(&self) -> (Vec2d, Vec2d, Vec2d) {
let nose = self.geometry[1];
let rot = rotate_radians(self.rotation);
let trans = translate(self.position);
let tmat = multiply(trans, rot);
(transform_pos(tmat, nose), transform_vec(rot, [1.0,0.0]), self.velocity)
}
}