Hi Welcome to the tutorial number 6 of our android 2d car Game in this
tutorial we will finally create our Game Controller class so you might
probably ask what this class can do in our game, well in this class we
will initialize all of our game object that we will be render later on to
our game world, and also here we implement the logic of the game.
such as positioning the player,enemy,adding score,difficulty and so on,
to begin creating controller class I declare all the objects that is needed
for this kind of game, since we are developing a Car game, I declare
different types of car that will represent as enemy.This enemy classes
are already created from the previous tutorial so if you want to know
how to create different types of enemy you can watch the previous
video which you can access from the playlist of my channel.the enemy
cars attribute that I declare are the truck,police,blackViper,player,MiniVAn,Taxi,Ambulance. all of this class
are pass as parameter in the Array so we can create multiple instance in
each of this class.next is I create a timer that will be check whether its
time to respawn our enemy's each one of this car has a different
schedule of respawn time so they will not appear in one place of the other's.
after setting up time and respawning enemy, I position the player to be
at the center but bottom in our screen. I've already created the
method that won't allow our player to go beyond our world, this means
that we keep blocking our player to leave the game world during game
play…for more info just watch my video above.
tutorial we will finally create our Game Controller class so you might
probably ask what this class can do in our game, well in this class we
will initialize all of our game object that we will be render later on to
our game world, and also here we implement the logic of the game.
such as positioning the player,enemy,adding score,difficulty and so on,
to begin creating controller class I declare all the objects that is needed
for this kind of game, since we are developing a Car game, I declare
different types of car that will represent as enemy.This enemy classes
are already created from the previous tutorial so if you want to know
how to create different types of enemy you can watch the previous
video which you can access from the playlist of my channel.the enemy
cars attribute that I declare are the truck,police,blackViper,player,MiniVAn,Taxi,Ambulance. all of this class
are pass as parameter in the Array so we can create multiple instance in
each of this class.next is I create a timer that will be check whether its
time to respawn our enemy's each one of this car has a different
schedule of respawn time so they will not appear in one place of the other's.
after setting up time and respawning enemy, I position the player to be
at the center but bottom in our screen. I've already created the
method that won't allow our player to go beyond our world, this means
that we keep blocking our player to leave the game world during game
play…for more info just watch my video above.
package game;
import settings.DifficultyLevel;
import settings.GameManager;
import assets.AssetsDescriptors;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.Pools;
import com.ninal.game.GdxGame;
import config.GameConfig;
import entities.Ambulance;
import entities.BlackViper;
import entities.MiniVan;
import entities.Player;
import entities.Police;
import entities.Taxi;
import entities.Truck;
public class GameController {
private static final Logger log = new Logger(
GameController.class.getSimpleName(), Logger.DEBUG);
private final GdxGame carAudi;
private final AssetManager manager;
private Player player;
private Police police;
private final Array<Police> policeArray = new Array<Police>();
private final Pool<Police> poolArrayPolice = Pools.get(Police.class, 1);
private Ambulance ambulance;
private final Array<Ambulance> ambulanceArray = new Array<Ambulance>(1);
private final Pool<Ambulance> poolAmbulanceArray = Pools.get(
Ambulance.class, 1);
private Taxi taxi;
private final Array<Taxi> taxiArray = new Array<Taxi>();
private final Pool<Taxi> poolArrayTaxi = Pools.get(Taxi.class, 1);
private BlackViper blackViper;
private final Array<BlackViper> blackViperArray = new Array<BlackViper>(1);
private final Pool<BlackViper> poolArrayBlackViper = Pools.get(
BlackViper.class, 1);
private Truck truck;
private final Array<Truck> truckArray = new Array<Truck>(1);
private final Pool<Truck> poolTruck = Pools.get(Truck.class, 1);
private MiniVan van;
private final Array<MiniVan> minivanArray = new Array<MiniVan>(1);
private final Pool<MiniVan> poolMiniVanArray = Pools.get(MiniVan.class, 1);
private float startPlayerX = GameConfig.WORLD_WIDTH / 2;
private float startPlayerY = 1;
private static final float X_MAX_SPEED = 0.05f;
private float ambulanceTimer;
private float ScoreTimer;
private int score;
private int displayScore;
private float policeTimer;
private float taxiTimer;
private float blackViperTimer;
private float truckTimer;
private float vanTimer;
private float xSpeed = 0;
private float scrollAmount = 0.16f;
private Music gameMusic;
private Sound explode;
private Sound engine_loop;
private Sound explode_mini;
private int Life = GameConfig.PLAYER_LIFE;
private boolean alive = true;
private ParticleEffect flameParticle;
private ParticleEffect enemyParticle;
private ParticleEffect explodeEffect;
private ParticleEffect playerExplodeEffects;
public GameController(GdxGame carAudi) {
this.carAudi = carAudi;
this.manager = carAudi.getManager();
init();
}
private void init() {
player = new Player();
player.setPosition(startPlayerX, startPlayerY);
truck = new Truck();
truck.setPosition(GameConfig.WORLD_WIDTH - truck.getWidth(),
GameConfig.WORLD_HEIGHT);
police = new Police();
police.setPosition(GameConfig.WORLD_WIDTH - police.getWidth(),
GameConfig.WORLD_HEIGHT);
ambulance = new Ambulance();
ambulance.setPosition(GameConfig.WORLD_WIDTH - ambulance.getWidth(),
GameConfig.WORLD_HEIGHT);
taxi = new Taxi();
taxi.setPosition(GameConfig.WORLD_WIDTH - taxi.getWidth(),
GameConfig.WORLD_HEIGHT);
blackViper = new BlackViper();
blackViper.setPosition(GameConfig.WORLD_WIDTH - blackViper.getWidth(),
GameConfig.WORLD_HEIGHT);
van = new MiniVan();
van.setPosition(GameConfig.WORLD_WIDTH - van.getWidth(),
GameConfig.WORLD_HEIGHT);
gameMusic = manager.get(AssetsDescriptors.GAME_SOUNDS);
explode = manager.get(AssetsDescriptors.EXPLODE_SOUND);
explode_mini = manager.get(AssetsDescriptors.EXPLODE_MINI_SOUND);
engine_loop = manager.get(AssetsDescriptors.ENGINE_SOUND);
flameParticle = manager.get(AssetsDescriptors.AUDI_EFFECTS);
enemyParticle = manager.get(AssetsDescriptors.ENEMY_EFFECTS);
explodeEffect = manager.get(AssetsDescriptors.EXPLODE_EFFECTS);
playerExplodeEffects = manager.get(AssetsDescriptors.PLAYER_EXPLODE_EFFECTS);
playerExplodeEffects.setPosition(GameConfig.WORLD_WIDTH - player.getWidth(),
GameConfig.WORLD_HEIGHT/2);
enemyParticle.setPosition(
GameConfig.WORLD_WIDTH - ambulance.getWidth(),
GameConfig.WORLD_HEIGHT);
explodeEffect.setPosition(GameConfig.WORLD_WIDTH - ambulance.getWidth(), GameConfig.WORLD_HEIGHT/2);
enemyParticle.setPosition(GameConfig.WORLD_WIDTH - police.getWidth(),
GameConfig.WORLD_HEIGHT);
enemyParticle.setPosition(
GameConfig.WORLD_WIDTH - blackViper.getWidth(),
GameConfig.WORLD_HEIGHT);
enemyParticle.setPosition(GameConfig.WORLD_WIDTH - taxi.getWidth(),
GameConfig.WORLD_HEIGHT);
enemyParticle.setPosition(GameConfig.WORLD_WIDTH - truck.getWidth(),
GameConfig.WORLD_HEIGHT);
enemyParticle.setPosition(GameConfig.WORLD_WIDTH - van.getWidth(),
GameConfig.WORLD_HEIGHT);
}
public boolean isGameOver(){
return Life <= 0;
}
// ==Player update
private void updatePlayerMove() {
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isTouched(0)) {
xSpeed = X_MAX_SPEED;
player.setX(player.getX() + xSpeed);
flameParticle.start();
engine_loop.play(0.1f);
} else if (Gdx.input.isKeyPressed(Input.Keys.LEFT)
|| Gdx.input.isTouched(1)) {
xSpeed = -X_MAX_SPEED;
player.setX(player.getX() + xSpeed);
flameParticle.start();
engine_loop.play(0.1f);
}
blockPlayerToLeaveWorld();
}
// ==block player from leaving world==
private void blockPlayerToLeaveWorld() {
float PlayerX = MathUtils.clamp(player.getX(), player.getWidth()
- GameConfig.PLAYER_SIZE,
GameConfig.WORLD_WIDTH - player.getWidth());
player.setPosition(PlayerX, player.getY());
flameParticle.setPosition(player.getX() + player.getWidth() / 2,
player.getY() + player.getHeight() / 2);
playerExplodeEffects.setPosition(player.getX()+player.getWidth()/2,
player.getY()+player.getHeight()/2);
}
public void update(float dt) {
if(isGameOver()){
log.debug("Game Over !!!");
return;
}
updateScore(dt);
displayScore(dt);
updatePlayerMove();
updateAmbulance(dt);
updatePolice(dt);
updateTaxi(dt);
updateblackViper(dt);
updateTruck(dt);
updateMiniVan(dt);
flameParticle.update(dt);
enemyParticle.update(dt);
gameMusic.play();
if(isAmbulanceCollidingPlayer()){
log.debug("collision detected !!!");
explode_mini.play();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
GameManager.GAME_MANAGER.updateHighScore(score);
}
else{
restart();
}
}
if(isBlackViperCollidePlayer()){
log.debug("collision detected !!!");
explode_mini.play();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
}
}
if(isMiniVanCollidePlayer()){
log.debug("collision detected !!!");
explode_mini.play();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
}
}
if(isPoliceCollidePlayer()){
log.debug("collision detected !!!");
explode_mini.play();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
}
}
if(isTaxiCollideWithPlayer()){
log.debug("collision detected !!!");
explode_mini.play();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
}
}
if(isTruckCollideWithPlayer()){
log.debug("collision detected !!!");
explode_mini.play();
gameMusic.stop();
Life--;
if(isGameOver()){
log.debug("Game Over !!!");
scrollAmount = 0;
gameMusic.stop();
engine_loop.stop();
}
}
}
private void updateScore(float dt) {
ScoreTimer +=dt;
if(ScoreTimer >= GameConfig.SCORE_TIMER){
score += MathUtils.random(1, 5);
ScoreTimer = 0;
}
}
private void displayScore(float delta){
if(displayScore < score){
displayScore = Math.min(score,
displayScore + (int)( 60 * delta));
}
}
// ==update AmbulanceLogic==
private void updateAmbulance(float dt) {
for (Ambulance ambulance : ambulanceArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
ambulance.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(ambulance.getX() + ambulance.getWidth()
/ 2, ambulance.getY() + ambulance.getHeight() / 2);
// explodeEffect.setPosition(ambulance.getX() + ambulance.getWidth()/2,
// ambulance.getY()+ambulance.getHeight()/2);
enemyParticle.start();
}
createAmbulance(dt);
removePassAmbulance();
}
private boolean isAmbulanceCollidingPlayer() {
for(Ambulance ambulance : ambulanceArray){
if(ambulance.isNotHit() && ambulance.isColliding(player)){
restart();
return true;
}
}
return false;
}
private boolean isBlackViperCollidePlayer(){
for(BlackViper viper : blackViperArray){
if(viper.isNotHit() && viper.isBlackViperCollidePlayer(player)){
return true;
}
}
return false;
}
private boolean isMiniVanCollidePlayer(){
for(MiniVan van : minivanArray){
if(van.isNotHit() && van.isMiniVanCollidePlayer(player)){
return true;
}
}
return false;
}
private boolean isPoliceCollidePlayer(){
for(Police police : policeArray){
if(police.isNotHit() && police.isPoliceColliding(player)){
return true;
}
}
return false;
}
private boolean isTaxiCollideWithPlayer(){
for(Taxi taxi : taxiArray){
if(taxi.isNotHit() && taxi.isTaxiCollidePlayer(player)){
return true;
}
}
return false;
}
private boolean isTruckCollideWithPlayer(){
for(Truck truck : truckArray){
if(truck.isNotHit() && truck.isTruckCollidePlayer(player)){
return true;
}
}
return false;
}
// ==update MiniVanLogic==
private void updateMiniVan(float dt) {
for (MiniVan van : minivanArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
van.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(van.getX() + van.getWidth() / 2,
van.getY() + van.getHeight() / 2);
enemyParticle.start();
}
createMiniVan(dt);
removePassMiniVan();
}
// == update Police Logic==
private void updatePolice(float dt) {
for (Police police : policeArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
police.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(police.getX() + police.getWidth() / 2,
police.getY() + police.getHeight() / 2);
enemyParticle.start();
}
createPolice(dt);
removePassedPolice();
}
// // == update Taxi Logic==
private void updateTaxi(float dt) {
for (Taxi taxi : taxiArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
taxi.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(taxi.getX() + taxi.getWidth() / 2,
taxi.getY() + taxi.getHeight() / 2);
enemyParticle.start();
}
createTaxi(dt);
removePassedTaxi();
}
// // == update BlackViper Logic==
private void updateblackViper(float dt) {
for (BlackViper blackViper : blackViperArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
blackViper.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(blackViper.getX() + blackViper.getWidth()
/ 2, blackViper.getY() + blackViper.getHeight() / 2);
enemyParticle.start();
}
createBlackViper(dt);
removePassedBlackViper();
}
// // == update Truck Logic==
private void updateTruck(float dt) {
for (Truck truck : truckArray) {
DifficultyLevel difficultyLevel = GameManager.GAME_MANAGER.getDifficultyLevel();
truck.updateEnemy(difficultyLevel.getDifficultySpeed());
enemyParticle.setPosition(truck.getX() + truck.getWidth() / 2,
truck.getY() + truck.getHeight() / 2);
enemyParticle.start();
}
createTruckArray(dt);
removePassedTruck();
}
// // == Create Array of Ambulance==
private void createAmbulance(float dt) {
ambulanceTimer += dt;
if (ambulanceTimer >= GameConfig.ENEMY_AMBULANCE_TIME) {
float min =3;
float max =3;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
Ambulance ambulance = poolAmbulanceArray.obtain();
ambulance.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
ambulance.setPosition(PositionX, PositionY);
ambulanceArray.add(ambulance);
if (ambulanceArray.size > 1) {
ambulanceArray.removeValue(ambulance, true);
ambulanceTimer = 0;
}
}
}
// // == create Array of Police
private void createPolice(float dt) {
policeTimer += dt;
if (policeTimer >= GameConfig.ENEMY_POLICE_SPAWN_TIME) {
float min = 2;
float max = 2;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
Police police = poolArrayPolice.obtain();
police.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
police.setPosition(PositionX, PositionY);
policeArray.add(police);
if (policeArray.size > 1) {
policeArray.removeValue(police, true);
policeTimer = 0;
}
}
}
// // == create Array of Taxi
private void createTaxi(float dt) {
taxiTimer += dt;
if (taxiTimer >= GameConfig.ENEMY_TAXI_SPAWN_TIME) {
float min =0;
float max =0;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
Taxi taxi = poolArrayTaxi.obtain();
taxi.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
taxi.setPosition(PositionX, PositionY);
taxiArray.add(taxi);
if (taxiArray.size > 1) {
taxiArray.removeValue(taxi, true);
taxiTimer = 0;
}
}
}
// // == create Array of BlackViper
private void createBlackViper(float dt) {
blackViperTimer += dt;
if (blackViperTimer >= GameConfig.ENEMY_BLACKVIPER_SPAWN_TIME) {
BlackViper blackViper = poolArrayBlackViper.obtain();
float min = 5;
float max = 5;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
blackViper.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
blackViper.setPosition(PositionX, PositionY);
blackViperArray.add(blackViper);
if (blackViperArray.size > 1) {
blackViperArray.removeValue(blackViper, true);
blackViperTimer = 0;
}
}
}
// // == create Array of Truck
private void createTruckArray(float dt) {
truckTimer += dt;
if (truckTimer >= GameConfig.ENEMY_TRUCK_SPAWN_TIME) {
Truck truck = poolTruck.obtain();
float min =1;
float max = 1;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
truck.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
truck.setPosition(PositionX, PositionY);
truckArray.add(truck);
if (truckArray.size > 1) {
truckArray.removeValue(truck, true);
truckTimer = 0;
}
}
}
// //== Create MiniVan Array ==
private void createMiniVan(float dt) {
vanTimer += dt;
if (vanTimer >= GameConfig.ENEMY_VAN_SPAWN_TIME) {
float min =4;
float max = 4;
float PositionX = MathUtils.random(min, max);
float PositionY = GameConfig.WORLD_HEIGHT;
MiniVan van = poolMiniVanArray.obtain();
van.setySpeed(GameConfig.DIFFICULTY_MEDIUM);
van.setPosition(PositionX, PositionY);
minivanArray.add(van);
if (minivanArray.size > 1) {
minivanArray.removeValue(van, true);
vanTimer = 0;
}
}
}
// // == Remove Passed Taxi==
private void removePassedTaxi() {
if (taxiArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
Taxi taxi = taxiArray.first();
if (taxi.getY() < minY) {
taxiArray.removeValue(taxi, true);
poolArrayTaxi.free(taxi);
}
}
}
// // == Remove Passed Truck==
private void removePassedBlackViper() {
if (blackViperArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
BlackViper blackViper = blackViperArray.first();
if (blackViper.getY() < minY) {
blackViperArray.removeValue(blackViper, true);
poolArrayBlackViper.free(blackViper);
}
}
}
// // == Remove Passed Ambulance==
private void removePassAmbulance() {
if (ambulanceArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
Ambulance ambulance = ambulanceArray.first();
if (ambulance.getY() < minY) {
ambulanceArray.removeValue(ambulance, true);
poolAmbulanceArray.free(ambulance);
}
}
}
// // == Remove Passed Police==
private void removePassedPolice() {
if (policeArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
Police police = policeArray.first();
if (police.getY() < minY) {
policeArray.removeValue(police, true);
poolArrayPolice.free(police);
}
}
}
// // == Remove Passed truck==
private void removePassedTruck() {
if (truckArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
Truck truck = truckArray.first();
if (truck.getY() < minY) {
truckArray.removeValue(truck, true);
poolTruck.free(truck);
}
}
}
// //== Remove Pass MiniVan==
private void removePassMiniVan() {
if (minivanArray.size > 0) {
float minY = -GameConfig.ENEMY_SIZE;
MiniVan van = minivanArray.first();
if (van.getY() < minY) {
minivanArray.removeValue(van, true);
poolMiniVanArray.free(van);
}
}
}
public float getAnimationTimer() {
return ambulanceTimer;
}
private void restart(){
poolAmbulanceArray.freeAll(ambulanceArray);
ambulanceArray.clear();
ambulanceTimer = 0;
// player.setPosition(startPlayerX, startPlayerY);
}
public float getStartPlayerX() {
return startPlayerX;
}
public void setStartPlayerX(float startPlayerX) {
this.startPlayerX = startPlayerX;
}
public float getStartPlayerY() {
return startPlayerY;
}
public float getTimer() {
return ambulanceTimer;
}
public Player getPlayer() {
return player;
}
public Music getGameMusic() {
return gameMusic;
}
public ParticleEffect getFlameParticle() {
return flameParticle;
}
public ParticleEffect getEnemyParticle() {
return enemyParticle;
}
public int getScore() {
return score;
}
public ParticleEffect getPlayerExplodeEffects() {
return playerExplodeEffects;
}
public Police getPolice() {
return police;
}
public Ambulance getAmbulance() {
return ambulance;
}
public Taxi getTaxi() {
return taxi;
}
public Array<Police> getArrayPolice() {
return policeArray;
}
public Pool<Police> getPoolArrayPolice() {
return poolArrayPolice;
}
public Array<Taxi> getArrayTaxi() {
return taxiArray;
}
public Pool<Taxi> getPoolArrayTaxi() {
return poolArrayTaxi;
}
public Array<Ambulance> getAmbulanceArray() {
return ambulanceArray;
}
public Pool<Ambulance> getPoolAmbulanceArray() {
return poolAmbulanceArray;
}
public Array<Truck> getTruckArray() {
return truckArray;
}
public Pool<Truck> getPoolTruck() {
return poolTruck;
}
public float getTruckTimer() {
return truckTimer;
}
public BlackViper getBlackViper() {
return blackViper;
}
public Array<BlackViper> getBlackViperArray() {
return blackViperArray;
}
public float getBlackViperTimer() {
return blackViperTimer;
}
public MiniVan getVan() {
return van;
}
public Array<MiniVan> getMinivanArray() {
return minivanArray;
}
public Pool<MiniVan> getPoolMiniVanArray() {
return poolMiniVanArray;
}
public float getVanTimer() {
return vanTimer;
}
public int getLife() {
return Life;
}
public float getScrollAmount() {
return scrollAmount;
}
public void setScrollAmount(float scrollAmount) {
this.scrollAmount = scrollAmount;
}
public ParticleEffect getExplodeEffect() {
return explodeEffect;
}
public void setExplodeEffect(ParticleEffect explodeEffect) {
this.explodeEffect = explodeEffect;
}
public int getDisplayScore() {
return displayScore;
}
}
0 Comments