Rect macro
[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
296187ca 7use common::Point2D;
6c5dd5cf 8use sdl2::gfx::primitives::DrawRenderer;
6ba7aef1 9use {SCREEN_HEIGHT, SCREEN_WIDTH};
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,
6ba7aef1
TW
48 (255.0 * (self.pos.y / SCREEN_HEIGHT as f64)) as u8,
49 128,
296187ca
TW
50 ));
51 let mut r = Rect::new(0, 0, size, size);
52 r.center_on(Point::new(self.pos.x as i32, self.pos.y as i32));
53 canvas.fill_rect(r).unwrap();
54 }
55}
6c5dd5cf 56
6c5dd5cf
TW
57pub struct CircleBoll {
58 pub boll: SquareBoll,
59}
60
61impl CircleBoll {
62 pub fn new(pos: Point2D<f64>, vel: Point2D<f64>) -> CircleBoll {
63 CircleBoll {
6ba7aef1 64 boll: SquareBoll { pos, vel },
6c5dd5cf
TW
65 }
66 }
67}
68
69impl Boll for CircleBoll {
70 fn update(&mut self) {
71 self.boll.update();
72 }
73
a4088bfb 74 fn draw(&self, canvas: &mut Canvas<Window>, size: u32) {
6c5dd5cf 75 let val = 255 - std::cmp::min(255, (self.boll.vel.length() * 20.0) as u8);
6ba7aef1
TW
76 canvas
77 .filled_circle(
78 self.boll.pos.x as i16,
79 self.boll.pos.y as i16,
80 size as i16,
81 Color::RGBA(val, val, val, 128),
82 )
83 .unwrap();
6c5dd5cf
TW
84 }
85}