Moved app to game
[kaka/rust-sdl-test.git] / src / boll.rs
CommitLineData
296187ca
TW
1use sdl2::pixels::Color;
2use sdl2::rect::Point;
3use sdl2::rect::Rect;
4use sdl2::render::Canvas;
5use sdl2::video::Window;
6
7use {SCREEN_HEIGHT, SCREEN_WIDTH};
8use common::Point2D;
6c5dd5cf 9use sdl2::gfx::primitives::DrawRenderer;
296187ca 10
c315bb31
TW
11pub trait Boll {
12 fn update(&mut self);
a4088bfb 13 fn draw(&self, canvas: &mut Canvas<Window>, size: u32);
c315bb31
TW
14}
15
16pub struct SquareBoll {
296187ca
TW
17 pub pos: Point2D<f64>,
18 pub vel: Point2D<f64>,
19}
20
c315bb31
TW
21impl Boll for SquareBoll {
22 fn update(&mut self) {
296187ca
TW
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
a4088bfb 44 fn draw(&self, canvas: &mut Canvas<Window>, size: u32) {
296187ca
TW
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}
6c5dd5cf
TW
55
56
57pub struct CircleBoll {
58 pub boll: SquareBoll,
59}
60
61impl 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
72impl Boll for CircleBoll {
73 fn update(&mut self) {
74 self.boll.update();
75 }
76
a4088bfb 77 fn draw(&self, canvas: &mut Canvas<Window>, size: u32) {
6c5dd5cf
TW
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}