about summary refs log tree commit diff stats
path: root/src/enemy.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/enemy.c')
-rw-r--r--src/enemy.c67
1 files changed, 40 insertions, 27 deletions
diff --git a/src/enemy.c b/src/enemy.c
index 0f73a55..47e2438 100644
--- a/src/enemy.c
+++ b/src/enemy.c
@@ -1,36 +1,49 @@
 #include "pong.h"
+#include <SDL2/SDL_atomic.h>
 
 void enemy(struct Players *Enemy, struct Balls ball) {
-	if (Enemy->NextTick <= SDL_AtomicGet(&Ticks)) {
-		if (!CheckCollisionRecs(ball.HitBox, Enemy->BallDetector)) {
-			if (Enemy->Y+120 > ball.Y) {
-				Enemy->Direction = 0;
-			} else if (Enemy->Y < ball.Y) {
-				Enemy->Direction = 1;
-			}
-		} else {
-			Enemy->Direction = 3;
+	int CurrentTick = SDL_AtomicGet(&Ticks);
+	int RunThisManyTimes;
+	if (Enemy->NextTick <= CurrentTick) {
+		if(CurrentTick > Enemy->NextTick) {
+			RunThisManyTimes = (CurrentTick - Enemy->NextTick);
 		}
-		switch(Enemy->Direction) {
-			case 0:
-				Enemy->Y -= 15;
-				break;
-			case 1:
-				Enemy->Y += 15;
-				break;
-			default:
-				break;
+		for (int i = 0; i <= RunThisManyTimes; i++) {
+			// Changes direction
+			if (!CheckCollisionRecs(ball.HitBox, Enemy->BallDetector)) {
+				if (Enemy->Y+120 > ball.Y) {
+					Enemy->Direction = 0;
+				} else if (Enemy->Y < ball.Y) {
+					Enemy->Direction = 1;
+				}
+			} else {
+				Enemy->Direction = 3;
+			}
+
+			// Moves
+			switch(Enemy->Direction) {
+				case 0:
+					Enemy->Y -= 15;
+					break;
+				case 1:
+					Enemy->Y += 15;
+					break;
+				default:
+					break;
+			}
+
+			// Prevents from going off screen.
+			if ( Enemy->Y > 480 ) {
+				Enemy->Y = 480;
+			} else if (Enemy->Y < 0) {
+				Enemy->Y = 0;
+			}
+			
+			// Updates hitbox and detector
+			Enemy->HitBox.y = Enemy->Y;
+			Enemy->BallDetector.y = Enemy->Y+80;
 		}
 		Enemy->NextTick = SDL_AtomicGet(&Ticks)+1;
 	}
-
-	// Prevents from going off screen.
-	if ( Enemy->Y > 480 ) {
-		Enemy->Y = 480;
-	} else if (Enemy->Y < 0) {
-		Enemy->Y = 0;
-	}
-	Enemy->HitBox.y = Enemy->Y;
-	Enemy->BallDetector.y = Enemy->Y+80;
 	return;
 }