Noticias

¡RECUERDA QUE SI ERES UN NUEVO USUARIO, DEBES PRESENTARTE PARA PODER PUBLICAR MENSAJES! | TENEMOS CANAL OFICIAL DE TELEGRAM: t.me/unity3dspain

Solucionado: Duda sobre Puzzle de conexiones de nodos.

Iniciado por Antonio, Octubre 12, 2015, 02:16:37 PM

Tema anterior - Siguiente tema
Octubre 12, 2015, 02:16:37 PM Ultima modificación: Octubre 12, 2015, 03:38:48 PM por Antonio
Buenos días.

Estoy intentando hacer un puzzle, se trata de un panel, con varios nodos, el jugador puede unir los distintos nodos con líneas para simular así un dibujo. El objetivo es que por el escenario, encontrará el dibujo, y tiene que recrearlo en este panel.using UnityEngine;
using System.Collections;


public class Puzzle_DrawerJoint_Manager : MonoBehaviour
{

GameObject Origin;

public GameObject Selector;
public Material Mat;
GameObject Sel;


public void ReceiveInput (GameObject input)
{
   if (Origin == null)
   {//Place the input in the origin
      Origin = input;
      Sel = Instantiate (Selector ,Origin.transform.position, Quaternion.identity) as GameObject;
      Sel.transform.localScale =
Vector3.one * 0.2f;
      Sel.transform.LookAt (Sel.transform.position + Vector3.up);
      Sel.transform.parent = Origin.transform;
      Sel.SendMessage ("Appear");
   }else{
      if (Origin == input)
      {//Clear the origin
         Sel.SendMessage ("Disappear");
         Origin = null;
      }else{//Place the input in the destiny and draw a line.
         bool Validated = true;
         Puzzle_DrawerJoint_Piece CodeOrigin = Origin.GetComponent <Puzzle_DrawerJoint_Piece>();
         Puzzle_DrawerJoint_Piece CodeDestiny = input.GetComponent <Puzzle_DrawerJoint_Piece>();

         foreach (GameObject cg in CodeOrigin.LinesDone)
         {
            if (input == cg)
 Validated = false;
         }

         foreach (GameObject cg in CodeDestiny.LinesDone)
         {
            if (Origin == cg)
 Validated = false;
         }

         if (Validated)//For Check if the line has not been already drawn.
         {//Draw the line
            CodeOrigin.LinesDone.Add (input);
            CodeDestiny.LinesDone.Add (Origin);

            GameObject go = new GameObject();
            go.transform.parent = Origin.transform;
            LineRenderer Ln = go.AddComponent<LineRenderer>() as LineRenderer;
            Ln.SetPosition (0, Origin.transform.position );
            Ln.SetPosition (1, input.transform.position );
            Ln.SetWidth (0.1f, 0.1f);
            Ln.material = Mat;
            Origin = null;
            Sel.SendMessage ("Disappear");
         }
      }
   }
}
} Pieces
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Puzzle_DrawerJoint_Piece : MonoBehaviour
{
Puzzle_DrawerJoint_Manager GraphicManager;
Puzzle_SeqManager LogicManager; //De momento no hace nada
public int MyID; //De momento no hace nada

public List <GameObject> LinesDone = new List<GameObject> ();

void Start ()
{
   GraphicManager = GetComponentInParent <Puzzle_DrawerJoint_Manager>();
   //LogicManager = GetComponentInParent <Puzzle_SeqManager>(); //De momento no hace nada
}

void OnMouseDown ()
{
   GraphicManager.ReceiveInput (gameObject);
   //LogicManager.ReceiveInput (MyID); //De momento no hace nada
}
}

Funcionamiento:
Cuando el jugador pulsa algún nodo, este envía una señal al manager y pueden pasar varias cosas:
- si no había ningún nodo seleccionado, se selecciona el nodo que ha pulsado ahora.
- si ya había algún nodo seleccionado, mira a ver si ha vuelto a pulsar el mismo nodo, en tal caso, el nodo se desselecciona.
- si ya había algún nodo seleecionado, y no ha pulsado 2 veces sobre el mismo nodo, comprueba si la línea ya existe. Si existe, pues no hace nada, si no existe, la crea.
(Cada nodo tiene una lista de nodos ya conectados para evitar crear múltiples líneas en la misma conexión, cada vez que se crea una). Ahora, no se me ocurre cómo hacer la comprobación. ¿Alguna idea? O.ò 

(El LogicManager es otro código que tengo que crea una clave, y verifica si se cumple, pero en este caso creo que no podré reutilizarlo porque ese código busca la clave lineal, (primero el primer valor, después el segundo, y tal, pero aquí en este puzzle, el jugador puede que empiece a dibujar por cualquier parte, así que seguramente tenga que crear un nuevo código para este puzzle en particular).


 

Octubre 12, 2015, 03:45:15 PM #1 Ultima modificación: Enero 01, 1970, 01:00:00 AM por Antonio
Ya lo pude solucionar.

Al final lo que he hecho es añadir una nueva lista a cada pieza, con los otros nodos que debe tener. Cada vez que hace una conexión nueva, comprueba si el objeto de esa conexión, esta en la lista de éxitos, si lo está el contador de esa pieza aumenta 1 punto, si no lo está, es porque es una conexión mala, el contador le resto 1 punto, (de modo que mientras tenga la conexión mala, nunca llegará al tope que tiene que llegar), La pieza pasa a ser satisfactoria cuando su contador es igual al número de nodos que hay en la lista de éxitos.

Si la pieza es satisfactoria, entonces le dice al Manager Lógico que sume 1 punto al contador general, así el Manager ya sabe que tiene 1 pieza bien, Cuando todas las piezas estén bien, es que el Puzzle está solucionado, (Hay que tener cuidado con el inicio, las piezas que no necesitan ninguna conexión pueden dar unos pocos problemas, por eso hice una función a parte).

Graphic Manager
using UnityEngine;
using System.Collections;


public class Puzzle_DrawerJoint_Manager : MonoBehaviour
{

GameObject Origin;

public GameObject Selector;
public Material Mat;
GameObject Sel;


public void ReceiveInput (GameObject input)
{
   if (Origin == null)
   {//Place the input in the origin
      Origin = input;
      Sel = Instantiate (Selector ,Origin.transform.position, Quaternion.identity) as GameObject;
      Sel.transform.localScale = Vector3.one * 0.2f;
      Sel.transform.LookAt (Sel.transform.position + Vector3.up);
      Sel.transform.parent = Origin.transform;
      Sel.SendMessage ("Appear");
   }else{
      if (Origin == input)
      {//Clear the origin
         Sel.SendMessage ("Disappear");
         Origin = null;
      }else{//Place the input in the destiny and draw a line.
         bool Validated = true;
         Puzzle_DrawerJoint_Piece CodeOrigin = Origin.GetComponent <Puzzle_DrawerJoint_Piece>();
         Puzzle_DrawerJoint_Piece CodeDestiny = input.GetComponent <Puzzle_DrawerJoint_Piece>();

         foreach (GameObject cg in CodeOrigin.LinesDone)
         {
            if (input == cg) Validated = false;
         }

         foreach (GameObject cg in CodeDestiny.LinesDone)
         {
            if (Origin == cg) Validated = false;
         }

         if (Validated)//For Check if the line has not been already drawn.
         {//Draw the line
            CodeOrigin.Add (input);
            CodeDestiny.Add (Origin);

            GameObject go = new GameObject();
            go.transform.parent = Origin.transform;
            LineRenderer Ln = go.AddComponent<LineRenderer>() as LineRenderer;
            Ln.SetPosition (0, Origin.transform.position );
            Ln.SetPosition (1, input.transform.position );
            Ln.SetWidth (0.1f, 0.1f);
            Ln.material = Mat;
            Origin = null;
            Sel.SendMessage ("Disappear");
         }
      }
   }
}
}


Piece
using System.Collections.Generic;

public class Puzzle_DrawerJoint_Piece : MonoBehaviour
{
Puzzle_DrawerJoint_Manager GraphicManager;
Puzzle_CubesManager LogicManager;
public List <GameObject> LinesGoal = new List<GameObject> ();
int GoalCount;
bool PointGiven;
public List <GameObject> LinesDone = new List<GameObject> ();

void InicPiece (bool RandomAction)//Random is unused in this puzzle piece.
{
   PointGiven = false;
   GoalCount = 0;

   GraphicManager = GetComponentInParent <Puzzle_DrawerJoint_Manager>();
   LogicManager = GetComponentInParent <Puzzle_CubesManager>();

   InitialCheck ();
}

void OnMouseDown ()
{
   if (LogicManager.Puzzle_Activated)   GraphicManager.ReceiveInput (gameObject);
}

public void Add (GameObject input)
{
   LinesDone.Add (input);
   CheckNewConnection (input);
}

void InitialCheck ()
{
   if (LinesGoal.Count == 0)
   {
      PointGiven = true;
      LogicManager.AddPoint ();
   }
}

void CheckNewConnection (GameObject input)
{
   bool found = false;

   foreach (GameObject sg in LinesGoal)
   {
      if (input == sg)
      {
         found = true;
         break;
      }
   }

   if (found)
   {
      GoalCount++;
   }else{
      GoalCount--;
   }

   if (GoalCount == LinesGoal.Count)
   {
      PointGiven = true;
      LogicManager.AddPoint ();
   }else{
      if (PointGiven)
      {
         LogicManager.SubstractPoint ();
         PointGiven = false;
      }
   }
}

public void ResetAction ()
{
   LinesDone.Clear ();
   foreach (Transform child in transform)
   {
      GameObject.Destroy(child.gameObject);
   }

   PointGiven = false;
   GoalCount = 0;      
   InitialCheck ();
}
}
Logic Manager
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Puzzle_CubesManager : MonoBehaviour
{
public bool Puzzle_Activated = true;
public bool RandomRotation = true;

public int CurrentPoints = 0;
int TotalPieces;
public GameObject EventsHolder;

public Button ExitButton;

public Cam_FreeLook CamCode;

void Start ()
{
   TotalPieces = transform.childCount;
   CamCode = Camera.main.GetComponentInParent <Cam_FreeLook>();
}


public void AddPoint ()
{
   CurrentPoints++;
   if (CurrentPoints == TotalPieces)//Lo ha completado.
   {
      if (Puzzle_Activated)
      {
         BroadcastMessage ("Finalizar", SendMessageOptions.DontRequireReceiver);//Desactiva las piezas.
         Puzzle_Activated = false;
         RandomRotation = false; //Para evitar que vuelva a girar al cargar partida.
         CamCode.ShowCursor (false);
         if (EventsHolder != null)
         {
            EventsHolder.BroadcastMessage ("DoActivateTrigger");
         }
      }else{//Lo ha completado el Random aleatorio.
         transform.GetChild (0).SendMessage ("InicPiece", true);//Gira una de las piezas otra vez.
      }
   }
}

public void SubstractPoint ()
{
   CurrentPoints--;
}

void DoActivateTrigger ()
{
   BroadcastMessage ("Inicializar", SendMessageOptions.DontRequireReceiver);
   Puzzle_Activated = true;
   CamCode.ShowCursor (true);
   if (ExitButton != null)   ExitButton.interactable = true;      
}

public void DoActivateAntiTrigger ()
{
   BroadcastMessage ("Finalizar", SendMessageOptions.DontRequireReceiver);
   if (ExitButton != null)   ExitButton.interactable = false;
   CamCode.ShowCursor (false);
}


public void LoadAnimating (int IncomeNodeID) //The position in the
{
   if (PlayerPrefs.HasKey (PlayerPrefs.GetInt ("ActiveSession")+"_"+Application.loadedLevelName+"_"+NodeID+"_PuzzleCube_Random"))
   {
      int RandomInt = PlayerPrefs.GetInt (PlayerPrefs.GetInt ("ActiveSession")+"_"+Application.loadedLevelName+"_"+NodeID+"_PuzzleCube_Random");
      if (RandomInt == 1)
      {
         RandomRotation = true;
      }else{
         RandomRotation = false;
      }
   }
   BroadcastMessage ("InicPiece", RandomRotation);
}

int NodeID;

public void SaveAnimating (int IncomeNodeID) //The position in the
{
   NodeID = IncomeNodeID;
   if (RandomRotation)
   {
      PlayerPrefs.SetInt (PlayerPrefs.GetInt ("ActiveSession")+"_"+Application.loadedLevelName+"_"+NodeID+"_PuzzleCube_Random", 1);
   }else{
      PlayerPrefs.SetInt (PlayerPrefs.GetInt ("ActiveSession")+"_"+Application.loadedLevelName+"_"+NodeID+"_PuzzleCube_Random", 0);
   }
}

public void ResetPuzzle ()
{
   CurrentPoints = 0;
   gameObject.BroadcastMessage ("ResetAction");
}
}
  Al menos el prototipo ya me funciona, ahora ya es ponerse a adornarlo para que sea más bonito. :D (Y crear los botones de la interfaz...)

Etiquetas: