about summary refs log blame commit diff stats
path: root/src/enemy.c
blob: b46ce15951f8ec437501c39fa5ff7c7d032b103c (plain) (tree)
1
2
3
4
5
6
7
8
9
                 
                            

                                                      
                                                
                                 


                                                                           
                 


                                                         









                                                                                    
                                   










                                                       
                                                             





                                                  
                                                         

                                                            
                 
                                                          
         
               
 
#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;
}