1 module comp.ball;
2 
3 import re;
4 import re.math;
5 import re.gfx;
6 import std.random;
7 import comp.score;
8 import comp.paddle;
9 import std.math;
10 
11 class Ball : Component, Updatable {
12     mixin Reflect;
13     private enum base_speed = 160;
14     private float speed = base_speed;
15     private float speed_up = 20;
16     private Vector2 direction;
17     private SpriteRenderer spr_ren;
18     private Paddle[] paddles;
19 
20     alias res = Core.default_resolution;
21 
22     override void setup() {
23         spr_ren = entity.get_component!SpriteRenderer;
24         respawn();
25     }
26 
27     void respawn() {
28         auto x_dir = [-1, 1].choice(Rng.rng);
29         auto y_dir = [-1, 1].choice(Rng.rng);
30         direction = Vector2(x_dir, y_dir);
31         speed = base_speed;
32 
33         entity.position2 = Vector2(res.x / 2, res.y / 2);
34     }
35 
36     void bounce_on(Paddle paddle) {
37         paddles ~= paddle;
38     }
39 
40     void update() {
41         // update direction
42         if (entity.position2.x + spr_ren.bounds.width / 2 >= res.x) {
43             direction = Vector2(-1, direction.y);
44         }
45 
46         if (entity.position2.x - spr_ren.bounds.width / 2 <= 0) {
47             direction = Vector2(1, direction.y);
48         }
49 
50         foreach (paddle; paddles) {
51             // check if within paddle Y
52             if (abs(entity.position2.y - paddle.entity.position2.y) < 5) {
53                 // check paddle X
54                 if (abs(entity.position2.x - paddle.entity.position2.x) < 60) {
55                     direction = Vector2(direction.x, -direction.y);
56                 }
57             }
58         }
59 
60         if (entity.position2.y + spr_ren.bounds.height / 2 >= res.y) {
61             // hit the bottom, ENEMY SCORE
62             Core.primary_scene.get_entity("score").get_component!Scoreboard().add_point_enemy();
63             respawn();
64         }
65 
66         if (entity.position2.y - spr_ren.bounds.height / 2 <= 0) {
67             // hit the top, PLAYER SCORE
68             Core.primary_scene.get_entity("score").get_component!Scoreboard().add_point_player();
69             respawn();
70         }
71 
72         entity.position2 = entity.position2 + (direction * speed * Time.delta_time);
73 
74         // increase speed
75         speed += Time.delta_time * speed_up;
76     }
77 }