Skip to content

Instantly share code, notes, and snippets.

@MartinAngeloni
Created August 31, 2017 18:24
Show Gist options
  • Save MartinAngeloni/404a974e68438f72a8f6d26389df14f7 to your computer and use it in GitHub Desktop.
Save MartinAngeloni/404a974e68438f72a8f6d26389df14f7 to your computer and use it in GitHub Desktop.
Juego en 2D con Unity C#. El gato que puede ser dos personajes a elegir, debe esquivar a los perros, obstáculos rígidos y ancianas con escobas hasta llegar a una fiambrera donde termina el juego.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AtunController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
//para destruir las latas de atun
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el enemigo
}
if (other.gameObject.tag == "Player" || other.gameObject.tag == "Player2")
{
Destroy(gameObject);//destruimos la lata de atun
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AtunGeneratorController : MonoBehaviour {
public GameObject atunPrefab;
public float generatorTimer = 1.75f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar atun
void CreateAtun()
{
Instantiate(atunPrefab, transform.position, Quaternion.identity);
}
public void StarGenerator()
{
InvokeRepeating("CreateAtun", 0f, 10); //invocamos un metodo con tiempo inicial y tiempo definido
}
public void CancelGenerator(bool clean = false)
{
CancelInvoke("CreateAtun");
if (clean)
{
Object[] allEnemys = GameObject.FindGameObjectsWithTag("Atun"); //buscamos todos los objetos en la escena con el tag Atun
foreach (GameObject atun in allEnemys)
{
Destroy(atun); //borramos todas las latas de atun, es opcional
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity;
}
//para destruir las cajas
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el enemigo
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxGeneratorController : MonoBehaviour {
public GameObject boxPrefabs;
public float generatorTimer = 1.75f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar refrigerador
void CreateBox()
{
Instantiate(boxPrefabs, transform.position, Quaternion.identity);
}
public void CancelGenerator(bool clean = false)
{
CancelInvoke("CreateBox");
if (clean)
{
Object[] allEnemys = GameObject.FindGameObjectsWithTag("Box"); //buscamos todos los objetos en la escena con el tag box
foreach (GameObject boxs in allEnemys)
{
Destroy(boxs); //borramos todos las cajas, es opcional
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
// Use this for initialization
void Start() {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity;
}
//para destruir los enemigos
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el enemigo
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyGeneratorController : MonoBehaviour {
public GameObject enemyPrefab;
public float generatorTimer = 20f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar enemigo
void CreateEnemy()
{
Instantiate(enemyPrefab, transform.position, Quaternion.identity);
}
public void CancelGenerator(bool clean = false)
{
CancelInvoke("CreateEnemy");
if (clean)
{
Object[] allEnemys = GameObject.FindGameObjectsWithTag("Enemy"); //buscamos todos los objetos en la escena con el tag enemy
foreach (GameObject enemy in allEnemys)
{
Destroy(enemy); //borramos todos los enemigos, es opcional
}
}
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FiambreriaGeneratorController : MonoBehaviour {
public GameObject fiambreriaPrefab;
public float generatorTimer = 1.75f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar fiambreria
void CreateDeli()
{
Instantiate(fiambreriaPrefab, transform.position, Quaternion.identity);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FiambreriaController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity;
}
//para destruir las latas de atun
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy" || other.gameObject.tag == "Player" || other.gameObject.tag == "Player2")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el enemigo
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement; //para reiniciar el juego una vez muerto
using System;
public class GameController : MonoBehaviour {
[Range(0f, 0.20f)] //limite a la velocidad Parallax
public float parallaxSpeed = 0.02f;
public RawImage background;
public RawImage platform;
public enum GameState { Idle, Playing, Ended};
public GameState gameState = GameState.Idle; //por defecto - jugador parado
public GameObject uiIdle; //pasamos UI Idle de Unity
public GameObject pointsIdle; //pasamos los puntos
public GameObject uiLife; // el ui de la vida
public GameObject enemy;
private Assets.Scripts.Points puntuaciones = new Assets.Scripts.Points();
private System.Random rnd = new System.Random();
public GameObject player; //jugador1
public GameObject player2; //jugador2
public GameObject enemyGenerator;
public GameObject refrigeratorGenerator;
public GameObject boxGenerator;
public GameObject atunGenerator;
public GameObject deliGenerator;
public GameObject abuelaGenerator;
Boolean generateEnemyRandom = true;
private int secondRespawnEnemy;
Boolean generateBoxRandom = true;
private int secondRespawnBox;
Boolean generateGrandMotherRandom = true;
private int secondRespawnGrandMother;
public static int secondRespawnFiambreria;
Boolean generateAtunRandom = true;
private int secondRespawnAtun;
Boolean generateRefrigeratorRandom = true;
private int secondRespawnRefrigerator;
Boolean fiambreriaRespawn = true;
Boolean isMoveRight = false;
Boolean isMoveLeft = false;
private AudioSource musicPlayer;
public AudioClip menuSong;
public AudioClip inGammingSong;
public float scaleTime = 6f; //para aumentar velocidad cada 6 segundos
public float scaleInc = .25f;
private int points = 0;
private int state = 0; //que segundo estoy posicionado
private int nextState = 0;
public Text pointsText; //puntuacion
public Text recordText; //record de puntuacion
public Text record2Text; //record de puntuacion
public Text recordText3; //record de puntuacion
public Text recordText4; //record de puntuacion
public Text recordText5; //record de puntuacion
public Text recordText6; //record de puntuacion
public Text recordText7; //record de puntuacion
public Text recordText8; //record de puntuacion
public Text recordText9; //record de puntuacion
public Text recordText10; //record de puntuacion
private float lifePoints = 9;
public Text lifeCountsText; //puntuacion de vida
// Use this for initialization
void Start () {
puntuaciones.initPoints();
musicPlayer = GetComponent<AudioSource>(); //recuperamos el audio y lo reproducimos al inicio
recordText.text = "BEST 1: " + puntuaciones.getMinMaxPoint(0).ToString(); //para dar la mayor puntuacion
musicPlayer.clip = menuSong;
musicPlayer.Play();
player.SetActive(true); //por defecto el jugador sera el gato 1
player2.SetActive(false);
secondRespawnFiambreria = ((int)(Time.time)) + 60;
mostrarPuntuaciones();
}
void mostrarPuntuaciones()
{
recordText3.text = "BEST 2: " + puntuaciones.getPuntaje(0).ToString();
recordText4.text = "BEST 3: " + puntuaciones.getPuntaje(1).ToString();
recordText5.text = "BEST 4: " + puntuaciones.getPuntaje(2).ToString();
recordText6.text = "BEST 5: " + puntuaciones.getPuntaje(3).ToString();
recordText7.text = "BEST 6: " + puntuaciones.getPuntaje(4).ToString();
}
void quitarPuntuaciones()
{
recordText3.text = "";
recordText4.text = "";
recordText5.text = "";
recordText6.text = "";
recordText7.text = "";
}
// Update is called once per frame
void Update () {
if(gameState == GameState.Idle)
{
pointsIdle.SetActive(false);
if (Input.GetKeyDown("a"))
{
player.SetActive(true);
player2.SetActive(false);
}
if (Input.GetKeyDown("b"))
{
player.SetActive(false);
player2.SetActive(true);
}
}
if (Input.GetKeyDown("right"))
{
isMoveRight = true;
}
if (Input.GetKeyUp("right"))
{
stopMoveRight();
}
if (Input.GetKeyDown("left"))
{
isMoveLeft = true;
}
if (Input.GetKeyDown("p"))
{
Debug.Log(puntuaciones.getMinMaxPoint(points));
puntuaciones.test();
}
if (Input.GetKeyUp("left"))
{
stopMoveLeft();
}
//empieza el juego
if (gameState == GameState.Idle && ((Input.GetMouseButtonDown(0)) || Input.GetKeyDown("up")))
{
uiIdle.SetActive(false); //desaparecemos el texto de inicio de juego
pointsIdle.SetActive(true); //aparecemos los puntos
gameState = GameState.Playing;
player.SendMessage("UpdateState", "playerIdle");
player2.SendMessage("UpdateState", "player2Idle");
musicPlayer.Stop(); //paramos la musica de menu
musicPlayer.clip = inGammingSong; //asignamos musica de juego
musicPlayer.Play(); //reproducimos la musica
//InvokeRepeating("GameTimeScale", scaleTime, scaleTime); //repetimos para aumentar la dificultad
}
else
{
//juego en marcha
if(gameState == GameState.Playing)
{
Parallax();
}
}
if(gameState == GameState.Ended)
{
refrigeratorGenerator.SendMessage("CancelGenerator", true);
boxGenerator.SendMessage("CancelGenerator", true);
atunGenerator.SendMessage("CancelGenerator", true);
enemyGenerator.SendMessage("CancelGenerator", true);
abuelaGenerator.SendMessage("CancelGenerator", true);
deliGenerator.SetActive(false);
if (puntuaciones.state)
{
puntuaciones.setPoints(points);
puntuaciones.state = false;
}
if (Input.GetKeyDown("up") || Input.GetMouseButtonDown(0))
{
StartCoroutine(waitSeconds(5f));
//RestarGame(); //llamamos al metodo que carga la escena al principio del juego
//simulando un reinicio de juego una vez muerto
}
//TODO
}
}
private IEnumerator waitSeconds(float seconds)
{
yield return new WaitForSeconds(seconds);
RestarGame();
}
//la plataforma y el fondo corren hacia el lado derecho
void Parallax()
{
if (((int)(Time.time)) != state) {
nextState = ((int)(Time.time));
}
if(state!= nextState)
{
state = nextState;
generateEnemy(state);
generateBox(state);
generateGrandMother(state);
generateAtun(state);
generateFiambreria(state);
generateRefrigerator(state);
}
if (isMoveRight)
{
moveRight();
}
if (isMoveLeft)
{
moveLeft();
}
}
void moveRight()
{
float finalSpeed = parallaxSpeed * Time.deltaTime;
background.uvRect = new Rect(background.uvRect.x + finalSpeed, 0f, 1f, 1f); //acelerar fondo
platform.uvRect = new Rect(platform.uvRect.x + finalSpeed * 5, 0f, 1f, 1f);
BoxController.velocity = 2.5f;
EnemyController.velocity = 5f;
GrandMotherController.velocity = 5f;
AtunController.velocity = 2.5f;
RefrigeratorController.velocity = 2.5f;
FiambreriaController.velocity = 2.5f;
}
void stopMoveRight()
{
isMoveRight = false;
BoxController.velocity = 0;
AtunController.velocity = 0f;
RefrigeratorController.velocity = 0f;
EnemyController.velocity = 2.5f;
GrandMotherController.velocity = 2.5f;
FiambreriaController.velocity = 0f;
}
void moveLeft()
{
float finalSpeed = parallaxSpeed * Time.deltaTime;
background.uvRect = new Rect(background.uvRect.x - (finalSpeed), 0f, 1f, 1f); //acelerar fondo
platform.uvRect = new Rect(platform.uvRect.x - (finalSpeed * 5), 0f, 1f, 1f);
BoxController.velocity = -2.5f;
EnemyController.velocity = 0f;
GrandMotherController.velocity = 0f;
AtunController.velocity = -2.5f;
RefrigeratorController.velocity = -2.5f;
FiambreriaController.velocity = -2.5f;
}
void stopMoveLeft()
{
isMoveLeft = false;
BoxController.velocity = 0;
AtunController.velocity = 0f;
RefrigeratorController.velocity = 0f;
EnemyController.velocity = 2.5f;
GrandMotherController.velocity = 2.5f;
FiambreriaController.velocity = 0f;
}
//Generar fiambreria
void generateFiambreria(int state)
{
if (fiambreriaRespawn && state == secondRespawnFiambreria)
{
deliGenerator.SendMessage("CreateDeli");
fiambreriaRespawn = false;
}
}
//Generar Atun
void generateAtun(int state)
{
System.Object[] only = GameObject.FindGameObjectsWithTag("Atun");
if (!generateAtunRandom && state >= secondRespawnAtun && only.Length == 0)
{
atunGenerator.SendMessage("CreateAtun");
generateAtunRandom = true;
}
if (generateAtunRandom)
{
secondRespawnAtun = state + rnd.Next(3, 12);
//Debug.Log(secondRespawnAtun);
generateAtunRandom = false;
}
}
//Generar Refrigeradores
void generateRefrigerator(int state)
{
System.Object[] only = GameObject.FindGameObjectsWithTag("Refrigerator");
if (!generateRefrigeratorRandom && state >= secondRespawnRefrigerator && only.Length == 0)
{
refrigeratorGenerator.SendMessage("CreateRefrigerator");
generateRefrigeratorRandom = true;
}
if (generateRefrigeratorRandom)
{
secondRespawnRefrigerator = state + rnd.Next(3, 12);
//Debug.Log(secondRespawnRefrigerator);
generateRefrigeratorRandom = false;
}
}
//Generar abuelas
void generateGrandMother(int state)
{
System.Object[] only = GameObject.FindGameObjectsWithTag("Grandmother");
if (!generateGrandMotherRandom && state >= secondRespawnGrandMother && only.Length == 0)
{
abuelaGenerator.SendMessage("CreateGrandmother");
generateGrandMotherRandom = true;
}
if (generateGrandMotherRandom)
{
secondRespawnGrandMother = state + rnd.Next(3, 12);
//Debug.Log(secondRespawnGrandMother);
generateGrandMotherRandom = false;
}
}
//Generar Cajas
void generateBox(int state)
{
System.Object[] only = GameObject.FindGameObjectsWithTag("Box");
if (!generateBoxRandom && state >= secondRespawnBox && only.Length == 0)
{
boxGenerator.SendMessage("CreateBox");
generateBoxRandom = true;
}
//Debug.Log(only.Length);
if (generateBoxRandom)
{
secondRespawnBox = state + rnd.Next(3, 12);
//Debug.Log(secondRespawnBox);
generateBoxRandom = false;
}
}
//Generar enemigos
void generateEnemy(int state)
{
System.Object[] only = GameObject.FindGameObjectsWithTag("Enemy");
if (!generateEnemyRandom && state >= secondRespawnEnemy && only.Length == 0)
{
enemyGenerator.SendMessage("CreateEnemy");
generateEnemyRandom = true;
}
if (generateEnemyRandom) {
secondRespawnEnemy = state + rnd.Next(3,12);
//Debug.Log(secondRespawnEnemy);
generateEnemyRandom = false;
}
}
public void RestarGame()
{
fiambreriaRespawn = true;
SceneManager.LoadScene("principal"); //para cargar una escena
}
//para aumentar la dificultad
void GameTimeScale()
{
Time.timeScale += scaleInc;
// Debug.Log("Increase speed");
}
//para detener el aumento del tiempo
public void ResetTimeScale()
{
CancelInvoke("GameTimeScale");
Time.timeScale = 1f;
//Debug.Log("Time Reset");
}
//aumentar los puntos
public void IncreasePoints()
{
//metodo que incrementa los puntos
points++;
pointsText.text = points.ToString();
//dsp de incrementar, lo mostramos por pantalla
//pointsText.text = points.ToString();
if(puntuaciones.getMinMaxPoint(points) > int.Parse(recordText.text))
{
recordText.text = "BEST: " + puntuaciones.getMinMaxPoint(points); //guardamos la puntuacion mas grande
SaveScore(points); //guardamos la puntuacion
}
}
//dar puntos por refrigerador
public void IncreasePointsRefrigerator()
{
points = points + 50; //100 pts por heladera capturada
pointsText.text = points.ToString();
}
//obtener mayor puntuacion
public int GetMaxScore()
{
return PlayerPrefs.GetInt("Max Points", 0); //cero porque asi sera al comienzo
}
//guardar la puntuacion
public void SaveScore(int currentPoints)
{
PlayerPrefs.SetInt("Max Points", currentPoints); //currentPoints es la puntcuacion que queremos guardar
PlayerPrefs.SetInt("Max Points2", currentPoints);
}
//metodo que decrementa las vidas del gato
public void DecreaseLifePoints()
{
lifePoints = lifePoints - 0.5f;
lifeCountsText.text = lifePoints.ToString();
}
//decimos que termino el juego cuando llega a la fiambreria
public void ChangeGameState(bool end = false)
{
if (end == true)
{
gameState = GameState.Ended;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrandMotherController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
//para destruir los enemigos
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el enemigo
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrandMotherGeneratorController : MonoBehaviour {
public GameObject grandMotherPrefab;
public float generatorTimer = 1.75f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar abuela
void CreateGrandmother()
{
Instantiate(grandMotherPrefab, transform.position, Quaternion.identity);
}
public void CancelGenerator(bool clean = false)
{
CancelInvoke("CreateGrandmother");
if (clean)
{
Object[] allEnemys = GameObject.FindGameObjectsWithTag("Grandmother"); //buscamos todos los objetos en la escena con el tag enemy
foreach (GameObject grandma in allEnemys)
{
Destroy(grandma); //borramos todos los enemigos, es opcional
}
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player2Controller : MonoBehaviour {
private Animator animator;
public GameObject game; //para importar el gameController para finalizar su estado playing a ende
public GameObject enemyGenerator;
public AudioClip jumpClip;
public AudioClip dieClip;
public AudioClip itemClip;
private AudioSource audioPlayer;
private float starY;
private int vida = 9;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>(); //detecta automaticamente el animador
audioPlayer = GetComponent<AudioSource>();
starY = transform.position.y; //posicion que tiene el personaje cuando toca el suelo
//para reproducir el sonido del salto solamente cuando toca el suelo
}
// Update is called once per frame
void Update () {
bool isGrounded = transform.position.y == starY; //significa que tocamos el suelo
bool gamePlaying = game.GetComponent<GameController>().gameState == GameController.GameState.Playing; //comprobamos si esta en juego para no revivr al personaje
if (isGrounded && gamePlaying && Input.GetKeyDown("up"))
{
UpdateState("player2Jump");
audioPlayer.clip = jumpClip; //asignmaos el sonido de salto
//reproducimos el sonido solo si esta en el suelo
audioPlayer.Play(); //reproducimos el sonido de salto
}
if (isGrounded && gamePlaying && Input.GetKeyDown("right"))
{
UpdateState("player2Run");
}
if (isGrounded && gamePlaying && Input.GetKeyUp("right"))
{
UpdateState("player2Idle");
}
if (isGrounded && gamePlaying && Input.GetKeyDown("left"))
{
UpdateState("player2RRun");
}
if (isGrounded && gamePlaying && Input.GetKeyUp("left"))
{
UpdateState("player2Idle");
}
}
public void UpdateState(string state = null) //por defecto seteamos a nulo
{
if (state != null)
{
animator.Play(state);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy" || other.gameObject.tag == "Box" || other.gameObject.tag == "Grandmother")
{
if(vida == 1) {
UpdateState("player2Die");
game.GetComponent<GameController>().gameState = GameController.GameState.Ended; //si muere terminamos el juego
enemyGenerator.SendMessage("CancelGenerator", true); //cancelamos invocacion de enemigos
game.SendMessage("DecreaseLifePoints");
game.SendMessage("ResetTimeScale");
game.GetComponent<AudioSource>().Stop(); //paramos la musica de fondo
audioPlayer.clip = dieClip; //le damos el clip de sonido de muerte
audioPlayer.Play(); //reproducimos el sonido de muerte
}
else
{
vida--;
game.SendMessage("DecreaseLifePoints");
UpdateState("player2Damage");
}
}
else if (other.gameObject.tag == "Point")
{
game.SendMessage("IncreasePoints");
}
else if (other.gameObject.tag == "Refrigerator")
{
audioPlayer.clip = itemClip;
audioPlayer.Play();
game.SendMessage("IncreasePointsRefrigerator");
Destroy(other); //destruimos el refrigerador
}
else if (other.gameObject.tag == "Atun")
{
audioPlayer.clip = itemClip;
audioPlayer.Play();
game.SendMessage("IncreasePoints");
Destroy(other); //destruimos la lata de atun
}
else if (other.gameObject.tag == "Deli")
{
UpdateState("player2Finished");
game.SendMessage("ChangeGameState", true);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
private Animator animator;
public GameObject game; //para importar el gameController para finalizar su estado playing a ende
public GameObject enemyGenerator;
public static bool isGrounded;
public AudioClip jumpClip;
public AudioClip dieClip;
public AudioClip itemClip;
private AudioSource audioPlayer;
private float starY;
private int vida = 9;
// Use this for initialization
void Start () {
animator = GetComponent<Animator>(); //detecta automaticamente el animador
audioPlayer = GetComponent<AudioSource>();
starY = transform.position.y; //posicion que tiene el personaje cuando toca el suelo
//para reproducir el sonido del salto solamente cuando toca el suelo
}
// Update is called once per frame
void Update () {
isGrounded = transform.position.y == starY; //significa que tocamos el suelo
bool gamePlaying = game.GetComponent<GameController>().gameState == GameController.GameState.Playing; //comprobamos si esta en juego para no revivr al personaje
if (isGrounded && gamePlaying && Input.GetKeyDown("up"))
{
UpdateState("playerJump");
audioPlayer.clip = jumpClip; //asignmaos el sonido de salto
//reproducimos el sonido solo si esta en el suelo
audioPlayer.Play(); //reproducimos el sonido de salto
}
if (isGrounded && gamePlaying && Input.GetKeyDown("right"))
{
UpdateState("playerRun");
}
if (isGrounded && gamePlaying && Input.GetKeyUp("right"))
{
UpdateState("playerIdle");
}
if (isGrounded && gamePlaying && Input.GetKeyDown("left"))
{
UpdateState("playerRRun");
}
if (isGrounded && gamePlaying && Input.GetKeyUp("left"))
{
UpdateState("playerIdle");
}
}
public void UpdateState(string state = null) //por defecto seteamos a nulo
{
if(state != null)
{
animator.Play(state);
}
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Enemy" || other.gameObject.tag == "Box" || other.gameObject.tag == "Grandmother")
{
if (vida == 1)
{
UpdateState("playerDie");
game.GetComponent<GameController>().gameState = GameController.GameState.Ended; //si muere terminamos el juego
enemyGenerator.SendMessage("CancelGenerator", true); //cancelamos invocacion de enemigos
game.SendMessage("DecreaseLifePoints");
game.SendMessage("ResetTimeScale");
game.GetComponent<AudioSource>().Stop(); //paramos la musica de fondo
audioPlayer.clip = dieClip; //le damos el clip de sonido de muerte
audioPlayer.Play(); //reproducimos el sonido de muerte
}
else
{
vida--;
game.SendMessage("DecreaseLifePoints");
UpdateState("playerDamage");
}
}
else if (other.gameObject.tag == "Point")
{
game.SendMessage("IncreasePoints");
}
else if (other.gameObject.tag == "Refrigerator")
{
audioPlayer.clip = itemClip;
audioPlayer.Play();
game.SendMessage("IncreasePointsRefrigerator");
Destroy(other); //destruimos el refrigerador
}
else if (other.gameObject.tag == "Atun")
{
audioPlayer.clip = itemClip;
audioPlayer.Play();
game.SendMessage("IncreasePoints");
Destroy(other); //destruimos la lata de atun
}
else if (other.gameObject.tag == "Deli")
{
game.SendMessage("ChangeGameState", true);
UpdateState("playerFinished");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace Assets.Scripts
{
class Points: MonoBehaviour
{
String[] jugadores = new String[5];
int[] puntajes = new int[5];
int index = 0;
public Boolean state;
public void initPoints()
{
state = true;
for (int x = 0; x < 5; x++) {
jugadores[x] = PlayerPrefs.GetString("jugador" + (x+1), " ");
puntajes[x] = PlayerPrefs.GetInt("puntaje" + (x + 1), 0);
}
}
public int getMinMaxPoint(int puntos)
{
for (int x = 5; x > 0; x--)
{
if (puntos < PlayerPrefs.GetInt("puntaje" + (x + 1), 0))
{
index = x;
return PlayerPrefs.GetInt("puntaje" + (x + 1), 0);
}
}
index = 0;
return PlayerPrefs.GetInt("puntaje1", 0);
}
public int setPoints(int puntos)
{
for (int x = 0; x < 5; x++)
{
if (puntos > PlayerPrefs.GetInt("puntaje" + (x + 1), 0))
{
puntajes[x] = PlayerPrefs.GetInt("puntaje" + (x + 1), 0);
PlayerPrefs.SetInt("puntaje" + (x + 1), puntos);
index = x;
return x;
}
}
return -1;
}
public void setName(String name)
{
jugadores[index] = name;
}
public void test()
{
Debug.Log(PlayerPrefs.GetInt("puntaje1", 0).ToString() + PlayerPrefs.GetInt("puntaje2", 0).ToString());
}
public String getName(int index)
{
return jugadores[index];
}
public int getPuntaje(int index)
{
return puntajes[index];
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RefrigeratorController : MonoBehaviour {
public static float velocity = 2.5f; //velocidad inicial
private Rigidbody2D rb2d;
public GameObject game;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>(); //componente que queremos recuperar
rb2d.velocity = Vector2.left * velocity; //vector que se mueve a la izquierda
}
// Update is called once per frame
void Update () {
rb2d.velocity = Vector2.left * velocity;
}
//para destruir los enemigos
//metodo generico, con los tags especificamos que destruir
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.tag == "Destroy")
{
//detectamos una colision con un Trigger
Destroy(gameObject);//destruimos el refrigerador
}
if(other.gameObject.tag == "Player" || other.gameObject.tag == "Player2")
{
Destroy(gameObject);//destruimos el refrigerador
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RefrigeratorGeneratorController : MonoBehaviour {
public GameObject refrigerator;
public float generatorTimer = 1.75f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//generar refrigerador
void CreateRefrigerator()
{
Instantiate(refrigerator, transform.position, Quaternion.identity);
}
public void CancelGenerator(bool clean = false)
{
CancelInvoke("CreateRefrigerator");
if (clean)
{
Object[] allEnemys = GameObject.FindGameObjectsWithTag("Refrigerator"); //buscamos todos los objetos en la escena con el tag enemy
foreach (GameObject refri in allEnemys)
{
Destroy(refri); //borramos todos los refrigeradores, es opcional
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment