about summary refs log tree commit diff stats
path: root/src/enemy.c
blob: b46ce15951f8ec437501c39fa5ff7c7d032b103c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "pong.h"
#include <SDL2/SDL_atomic.h>

void enemy(struct Players *Enemy, struct Balls ball) {
	int CurrentTick = SDL_AtomicGet(&Ticks);
	int RunThisManyTimes = 0;
	if (Enemy->NextTick <= CurrentTick) {
		if(CurrentTick > Enemy->NextTick) {
			RunThisManyTimes = (CurrentTick - Enemy->NextTick);
		}
		int i = 0;
		for (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;
	}
	return;
}