casse-brick latest
Ce projet est réalisé dans le cadre du cours de Programmation Avancée en M1 Informatique de l'université de Strasbourg.
Loading...
Searching...
No Matches
Ball.cpp
Go to the documentation of this file.
1//
2// Created by nicolas elfering on 08.05.24.
3//
4
5#include "Ball.h"
6
7Ball::Ball( int x, int y, int radius, const SDL_Color &color, const std::string& id)
8 : MovingObject(x, y, radius, id){
9 Velocity = {0,2};
11}
12
13void Ball::render(std::shared_ptr<SDL_Renderer> renderer, SDL_Color color1,SDL_Color color2) {
14 collider->render(renderer,color1,color2);
15}
16
17void Ball::move() {
18 collider->move({Velocity.x,Velocity.y});
19}
20
21void Ball::setVelocity(float dx, float dy) {
22 Velocity = {dx,dy};
23}
24
27 if(bounce_number==0){
28 Velocity.x /=2;
29 Velocity.y /=2;
30 }
31 float dx = collision.x - collider->p.x;
32 float dy = collision.y - collider->p.y;
33 float len = std::sqrt(dx * dx + dy * dy);
34 if (len <= 1) {
35 dx = 1.0f;
36 dy = 0.0f;
37 } else {
38 dx /= len;
39 dy /= len;
40 }
41
42 float dotProduct = Velocity.x * dx + Velocity.y * dy;
43 setVelocity( (Velocity.x - 2 * dotProduct * dx),(Velocity.y - 2 * dotProduct * dy));
44}
45
47 auto normalized = [] (point v){
48 float len = std::sqrt(std::pow(v.x, 2) + std::pow(v.y, 2));
49 if (len != 0.0f) {
50 return point{v.x/len, v.y/len};
51 }
52 return point();
53 };
54 auto dot = [] (point v1, point v2){
55 return v1.x*v2.x+v1.y*v2.y;
56 };
57
58 point vectNorm = normalized(vectDir);
59
60 point reflexion = normalized(vectNorm*2*dot(Velocity,vectNorm)-Velocity);
61
62 setVelocity(reflexion.x*2, reflexion.y*2);
63}
int bounce_number
Definition Ball.h:23
void move() override
Moves the ball according to its velocity.
Definition Ball.cpp:17
void render(std::shared_ptr< SDL_Renderer > renderer, SDL_Color color1, SDL_Color color2) override
Renders the ball on the screen.
Definition Ball.cpp:13
point Velocity
Definition Ball.h:22
Ball(int x, int y, int radius, const SDL_Color &color, const std::string &id)
Constructs a new Ball object.
Definition Ball.cpp:7
void handleCollision(point vect)
Handles collision with a single object.
Definition Ball.cpp:46
void setVelocity(float dx, float dy)
Sets the velocity of the ball.
Definition Ball.cpp:21
void handleCollisions(point collision) override
Handles collisions with other objects.
Definition Ball.cpp:25
std::shared_ptr< Collider > collider
The collider associated with the object.
The MovingObject class represents a moving colliding object.
The point struct represents a point in 2D space.
float y
The y-coordinate of the point.
float x
The x-coordinate of the point.