Use trait for boll variants
[kaka/rust-sdl-test.git] / src / boll.rs
1 use sdl2::pixels::Color;
2 use sdl2::rect::Point;
3 use sdl2::rect::Rect;
4 use sdl2::render::Canvas;
5 use sdl2::video::Window;
6
7 use {SCREEN_HEIGHT, SCREEN_WIDTH};
8 use common::Point2D;
9
10 pub trait Boll {
11     fn update(&mut self);
12     fn draw(&mut self, canvas: &mut Canvas<Window>, size: u32);
13 }
14
15 pub struct SquareBoll {
16     pub pos: Point2D<f64>,
17     pub vel: Point2D<f64>,
18 }
19
20 impl Boll for SquareBoll {
21     fn update(&mut self) {
22         self.vel.y += 0.1;
23         self.pos += self.vel;
24
25         if self.pos.x < 0.0 {
26             self.pos.x = -self.pos.x;
27             self.vel.x = -self.vel.x;
28         }
29         if self.pos.x > SCREEN_WIDTH as f64 {
30             self.pos.x = SCREEN_WIDTH as f64 - (self.pos.x - SCREEN_WIDTH as f64);
31             self.vel.x = -self.vel.x;
32         }
33         if self.pos.y < 0.0 {
34             self.pos.y = -self.pos.y;
35             self.vel.y = -self.vel.y;
36         }
37         if self.pos.y > SCREEN_HEIGHT as f64 {
38             self.pos.y = SCREEN_HEIGHT as f64 - (self.pos.y - SCREEN_HEIGHT as f64);
39             self.vel.y = -self.vel.y;
40         }
41     }
42
43     fn draw(&mut self, canvas: &mut Canvas<Window>, size: u32) {
44         canvas.set_draw_color(Color::RGBA(
45             255 - std::cmp::min(255, (self.vel.length() * 25.0) as u8),
46             (255.0 * (self.pos.x / SCREEN_WIDTH as f64)) as u8,
47             (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8, 128
48         ));
49         let mut r = Rect::new(0, 0, size, size);
50         r.center_on(Point::new(self.pos.x as i32, self.pos.y as i32));
51         canvas.fill_rect(r).unwrap();
52     }
53 }