Moved out objects from game module
[kaka/rust-sdl-test.git] / src / boll.rs
... / ...
CommitLineData
1use core::render::Renderer;
2use geometry::Point;
3use sdl2::gfx::primitives::DrawRenderer;
4use sdl2::rect::Rect;
5use {SCREEN_HEIGHT, SCREEN_WIDTH};
6
7pub trait Boll {
8 fn update(&mut self);
9 fn draw(&self, renderer: &mut Renderer, size: u32);
10}
11
12pub struct SquareBoll {
13 pub pos: Point<f64>,
14 pub vel: Point<f64>,
15}
16
17impl Boll for SquareBoll {
18 fn update(&mut self) {
19 self.vel.y += 0.1;
20 self.pos += self.vel;
21
22 if self.pos.x < 0.0 {
23 self.pos.x = -self.pos.x;
24 self.vel.x = -self.vel.x;
25 }
26 if self.pos.x > SCREEN_WIDTH as f64 {
27 self.pos.x = SCREEN_WIDTH as f64 - (self.pos.x - SCREEN_WIDTH as f64);
28 self.vel.x = -self.vel.x;
29 }
30 if self.pos.y < 0.0 {
31 self.pos.y = -self.pos.y;
32 self.vel.y = -self.vel.y;
33 }
34 if self.pos.y > SCREEN_HEIGHT as f64 {
35 self.pos.y = SCREEN_HEIGHT as f64 - (self.pos.y - SCREEN_HEIGHT as f64);
36 self.vel.y = -self.vel.y;
37 }
38 }
39
40 fn draw(&self, renderer: &mut Renderer, size: u32) {
41 renderer.canvas().set_draw_color((
42 255 - std::cmp::min(255, (self.vel.length() * 25.0) as u8),
43 (255.0 * (self.pos.x / SCREEN_WIDTH as f64)) as u8,
44 (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8,
45 128,
46 ));
47 let mut r = Rect::new(0, 0, size, size);
48 r.center_on((self.pos.x as i32, self.pos.y as i32));
49 renderer.canvas().fill_rect(r).unwrap();
50 }
51}
52
53pub struct CircleBoll {
54 pub boll: SquareBoll,
55}
56
57impl CircleBoll {
58 pub fn new(pos: Point<f64>, vel: Point<f64>) -> CircleBoll {
59 CircleBoll {
60 boll: SquareBoll { pos, vel },
61 }
62 }
63}
64
65impl Boll for CircleBoll {
66 fn update(&mut self) {
67 self.boll.update();
68 }
69
70 fn draw(&self, renderer: &mut Renderer, size: u32) {
71 let val = 255 - std::cmp::min(255, (self.boll.vel.length() * 20.0) as u8);
72 renderer
73 .canvas()
74 .filled_circle(
75 self.boll.pos.x as i16,
76 self.boll.pos.y as i16,
77 size as i16,
78 (val, val, val, 128),
79 )
80 .unwrap();
81 }
82}