summary refs log tree commit diff stats
path: root/src/ball.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/ball.c')
-rw-r--r--src/ball.c68
1 files changed, 68 insertions, 0 deletions
diff --git a/src/ball.c b/src/ball.c
new file mode 100644
index 0000000..7a9e7cb
--- /dev/null
+++ b/src/ball.c
@@ -0,0 +1,68 @@
+#include "raylib.h"
+#include "pong.h"
+
+void ball(Rectangle *Player, Rectangle *Enemy, struct Balls *Ball, int *PlayerScore, int *EnemyScore) {
+	
+	// Moves ball
+	Ball->Y += Ball->Angle;
+	if (Ball->Direction == LEFT) {
+		Ball->X -= Ball->Speed;
+	} else {
+		Ball->X += Ball->Speed;
+	}
+	// Moves hitbox with ball.
+	Ball->HitBox.x = Ball->X;
+	Ball->HitBox.y = Ball->Y;
+
+	// Check collisions against players.
+	if (CheckCollisionRecs(*Player, Ball->HitBox) && Ball->Direction == LEFT) {
+		Ball->Direction = RIGHT;
+		Ball->Speed *= 1.5f;
+        if (Ball->Speed > 40) {
+            Ball->Speed = 40;
+        }
+        if (Ball->Speed != 40) {
+		    Ball->Angle = GetRandomValue(-10, 10);
+        } else {
+            Ball->Angle = GetRandomValue(-20, 20);
+        }
+        play_audio(0);
+	}
+	if (CheckCollisionRecs(*Enemy, Ball->HitBox) && Ball->Direction == RIGHT) {
+		Ball->Direction = LEFT;
+		Ball->Speed *= 1.5f;
+       	if (Ball->Speed > 40) {
+	    	Ball->Speed = 40;
+	    }
+		if (Ball->Speed != 40) {
+		    Ball->Angle = GetRandomValue(-10, 10);
+        } else {
+            Ball->Angle = GetRandomValue(-30, 30);
+        }
+        play_audio(SOUND_BOUNCE);
+	}
+	
+	// Bounce ball if touches top or bottom of screen.
+	if ( (Ball->Y+32 >= 720 && Ball->Angle >=1) || (Ball->Y <= 0 && Ball->Angle <= -1) ) {
+		Ball->Angle *= -1;
+        play_audio(SOUND_BOUNCE);
+	}
+
+	// Calculates score and resets ball.
+	bool Scored = false;
+	if (Ball->X < 0) {
+		*EnemyScore += 1;
+		Scored = true;
+	} else if (Ball ->X > 1280) {
+		*PlayerScore += 1;
+		Scored = true;
+	}
+	if (Scored == true) {
+		Ball->X = 1280/2.0f;
+		Ball->Y = 720/2.0f;
+		Ball->Speed = 3.0f;
+		Ball->Angle = 0;
+	}
+
+	return;
+}
\ No newline at end of file