64be265cf6fd92798d418d65500cd7c96c191490
[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 use sdl2::gfx::primitives::DrawRenderer;
10
11 pub trait Boll {
12     fn update(&mut self);
13     fn draw(&self, canvas: &mut Canvas<Window>, size: u32);
14 }
15
16 pub struct SquareBoll {
17     pub pos: Point2D<f64>,
18     pub vel: Point2D<f64>,
19 }
20
21 impl Boll for SquareBoll {
22     fn update(&mut self) {
23         self.vel.y += 0.1;
24         self.pos += self.vel;
25
26         if self.pos.x < 0.0 {
27             self.pos.x = -self.pos.x;
28             self.vel.x = -self.vel.x;
29         }
30         if self.pos.x > SCREEN_WIDTH as f64 {
31             self.pos.x = SCREEN_WIDTH as f64 - (self.pos.x - SCREEN_WIDTH as f64);
32             self.vel.x = -self.vel.x;
33         }
34         if self.pos.y < 0.0 {
35             self.pos.y = -self.pos.y;
36             self.vel.y = -self.vel.y;
37         }
38         if self.pos.y > SCREEN_HEIGHT as f64 {
39             self.pos.y = SCREEN_HEIGHT as f64 - (self.pos.y - SCREEN_HEIGHT as f64);
40             self.vel.y = -self.vel.y;
41         }
42     }
43
44     fn draw(&self, canvas: &mut Canvas<Window>, size: u32) {
45         canvas.set_draw_color(Color::RGBA(
46             255 - std::cmp::min(255, (self.vel.length() * 25.0) as u8),
47             (255.0 * (self.pos.x / SCREEN_WIDTH as f64)) as u8,
48             (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8, 128
49         ));
50         let mut r = Rect::new(0, 0, size, size);
51         r.center_on(Point::new(self.pos.x as i32, self.pos.y as i32));
52         canvas.fill_rect(r).unwrap();
53     }
54 }
55
56
57 pub struct CircleBoll {
58     pub boll: SquareBoll,
59 }
60
61 impl CircleBoll {
62     pub fn new(pos: Point2D<f64>, vel: Point2D<f64>) -> CircleBoll {
63         CircleBoll {
64             boll: SquareBoll {
65                 pos,
66                 vel,
67             }
68         }
69     }
70 }
71
72 impl Boll for CircleBoll {
73     fn update(&mut self) {
74         self.boll.update();
75     }
76
77     fn draw(&self, canvas: &mut Canvas<Window>, size: u32) {
78         let val = 255 - std::cmp::min(255, (self.boll.vel.length() * 20.0) as u8);
79         canvas.filled_circle(self.boll.pos.x as i16, self.boll.pos.y as i16, size as i16, Color::RGBA(
80             val,
81             val,
82             val,
83             128,
84         )).unwrap();
85     }
86 }