about summary refs log tree commit diff stats
path: root/src/ball.c
blob: af210bb89d5251e7ca679a430d3f9acd33717c22 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "pong.h"

void ball(Rectangle *Player, Rectangle *Enemy, struct Balls *Ball, int *PlayerScore, int *EnemyScore) {
	
	bool NoEnemy = false;
	if (Enemy == NULL) {
		NoEnemy = true;
	}

	// Moves 
	int CurrentTick = SDL_AtomicGet(&Ticks);
	if(Ball->NextTick <= CurrentTick){
		int RunThisManyTimes = 0;
		if (CurrentTick > Ball->NextTick) {
			RunThisManyTimes = (CurrentTick - Ball->NextTick);
		}
		for (int i = 0; i <= RunThisManyTimes; i++) {
			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(-30, 30);
				}
				play_audio(0);
			}
			if (NoEnemy == false) {
				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);
			}
		}
		Ball->NextTick = SDL_AtomicGet(&Ticks)+1;
//		printf("%d,%d\n", SDL_AtomicGet(&Ticks), Ball->NextTick);
	}
//	printf("%d,%d\n", SDL_AtomicGet(&Ticks), Ball->NextTick);

	// Calculates score and resets ball.
	bool Scored = false;
	if (Ball->X < 0 && NoEnemy == false) {
		*EnemyScore += 1;
		Scored = true;
	} else if (Ball ->X > 1280 && NoEnemy == false) {
		*PlayerScore += 1;
		Scored = true;
	} else if (Ball->X > (1280-32) && NoEnemy == true) {
		*PlayerScore += 1;
		Scored = false;
		Ball->Direction = LEFT;
		play_audio(SOUND_PLAYER_SCORE);
	} 
	if (Scored == true) {
		Ball->X = 1280/2.0f;
		Ball->Y = 720/2.0f;
		Ball->Speed = 3.0f;
		Ball->Angle = 0;
	}

	return;
}