-1
\$\begingroup\$

I got this code and this code uses sprite as chess pieces. All I want to do is to use 3D game objects instead of sprite. And I am confused on how to do that. I already got the code and it is using sprite as chess pieces. I want to use 3D models as chess piece instead of 2D sprites. How do I convert these 2D sprites codes to 3D codes? I already used using public GameObjects as a solution but there are too many errors happening.

Here is my code

public class LuxChess2D : Engine {

  /// <summary>
  /// Pieces set.
  /// </summary>
  [Serializable]
  public class PieceSet
  {
    public Sprite Pawn;
    public Sprite Bishop;
    public Sprite Knight;
    public Sprite Rook;
    public Sprite Queen;
    public Sprite King;
    public Sprite Square;
  }

  /// <summary>
  /// White pieces.
  /// </summary>
  public PieceSet WhitePieces;

  /// <summary>
  /// Black pieces.
  /// </summary>
  public PieceSet BlackPieces;

  [HideInInspector]
  public Transform[] SquaresObj; //From 0-to 63
  public Transform CanvasTr; //Squares should be parented to the canvas
  public GameObject SquareObj; //Square prefab
  public Sprite NoPieceSprite; //If there is no piece then use this sprite for the piece image - should be transparent

  /// <summary>
  /// Comuputer thinking time. He will 'force' stop after this time.
  /// </summary>
  public int ComputerThinkingTime = 3;

  /// <summary>
  /// Starting FEn.
  /// </summary>
  public string StartingFen = FEN.Default;

  [HideInInspector]
  public int DragingFrom; //We are dragging piece from this position

  public UnityEvent OnWhiteTurn; //Event
  public UnityEvent OnBlackTurn; //Event

  //UI
  public Text GameStateUI;
  public InputField FENOutputUI;

  private void Start() {

    DragingFrom = -1; //Not dragging from any square
    SquaresObj = new Transform[64]; //Inti squares

    for (int i = 0; i < 64; i++)
    {
      int x= i%8;
      int y = i/8;

      //Create square
      GameObject obj = Instantiate(SquareObj, Vector3.zero, Quaternion.identity) as GameObject;
      obj.transform.SetParent(CanvasTr, true); //set parent
      obj.transform.localPosition = new Vector3(-244 + 64 * x, 204 - 64 * y, 0); //Position it

      PieceMover pm = obj.GetComponent<PieceMover>(); //Get piece component
      pm.index = i; //Set index 
      pm.manager = this; //Set manager reference

      if ((i + y) % 2 == 0) //Change sprites according to squares
      {
        obj.GetComponent<Image>().sprite = WhitePieces.Square; //White square
      }
      else
        obj.GetComponent<Image>().sprite = BlackPieces.Square; //Black square

      //Save a square in a squares array at right index
      SquaresObj[i] = obj.transform;
    }

    //Calls the init in the engine class
    InitChess(StartingFen);

    //Updates the board changes
    UpdateBoard();
  }

  /// <summary>
  /// Updates all pieces based on board pieces.
  /// </summary>
  public void UpdateBoard() {
    //Initialize grid
    for (int i = 0; i < 64; i++)
    {
      int piece = GetPieceAt(i);

      switch (piece)
      {
      //Button will shrink texture, which creates much better 'piece' effect
      case Defs.WPawn: CreatePiece(WhitePieces.Pawn, i); break;
      case Defs.WBishop: CreatePiece(WhitePieces.Bishop, i); break;
      case Defs.WKnight: CreatePiece(WhitePieces.Knight, i); break;
      case Defs.WRook: CreatePiece(WhitePieces.Rook, i); break;
      case Defs.WQueen: CreatePiece(WhitePieces.Queen, i); break;
      case Defs.WKing: CreatePiece(WhitePieces.King, i); break;
      case Defs.BPawn: CreatePiece(BlackPieces.Pawn, i); break;
      case Defs.BBishop: CreatePiece(BlackPieces.Bishop, i); break;
      case Defs.BKnight: CreatePiece(BlackPieces.Knight, i); break;
      case Defs.BRook: CreatePiece(BlackPieces.Rook, i); break;
      case Defs.BQueen: CreatePiece(BlackPieces.Queen, i); break;
      case Defs.BKing: CreatePiece(BlackPieces.King, i); break;
      case Defs.Empty:
        CreatePiece(NoPieceSprite, i);
        break;
      }
    }
  }

  private Squares LastSquare = Squares.None;
  public override void OnTurnSwitched() //Turn was switched
  { 

    //Who's turn?
    if (SideToPlay() == 1) //White
    {
      if (OnWhiteTurn != null)
        OnWhiteTurn.Invoke();
    }
    else {
      if (OnBlackTurn != null)
        OnBlackTurn.Invoke();
      ComputerPlay(ComputerThinkingTime); //Computer should play as black
    }

    GameStateUI.text = Regex.Replace(GameState().ToString(),"[A-Z]", " $0"); //Space before capital letter
    FENOutputUI.text = GetFen();

    //Check if in check
    Squares sq = IsInCheck();
    if (sq != Squares.None) { //If in check mark square
      LastSquare = sq;
      SquaresObj[(int)LastSquare].gameObject.GetComponent<Image>().color = new Color32(255,15,15,255);
    }
    else if (LastSquare != Squares.None) {//Remove last marked square
      SquaresObj[(int)LastSquare].gameObject.GetComponent<Image>().color = Color.white;
    }
  }

  private Vector2 origPieceSize = Vector2.zero;
  private void CreatePiece(Sprite piece, int index, float scale = 1f)
  {
    Image image = SquaresObj[index].GetChild(0).gameObject.GetComponent<Image>();

    //Get the size of the first piece and store it 
    if (origPieceSize == Vector2.zero)
      origPieceSize = image.rectTransform.sizeDelta;

    image.rectTransform.sizeDelta = origPieceSize*scale;
    image.sprite = piece;

  }

  private Squares LastSquareFrom = Squares.None;
  private Squares LastSquareTo = Squares.None;
  public override void OnComputerPlayed(int from, int to)
  {

    //Mark the squares that piece traveled
    SquaresObj[(int)from].gameObject.GetComponent<Image>().color = new Color32(73, 35, 0, 255);
    SquaresObj[(int)to].gameObject.GetComponent<Image>().color = new Color32(73, 30, 0, 255);

    //Reset colors
    if ((int)LastSquareFrom != from && (int)LastSquareFrom != to && LastSquareFrom != Squares.None)
    {
      SquaresObj[(int)LastSquareFrom].gameObject.GetComponent<Image>().color = Color.white;
    }

    if ((int)LastSquareTo != to && (int)LastSquareTo != from && LastSquareTo != Squares.None)
    {
      SquaresObj[(int)LastSquareTo].gameObject.GetComponent<Image>().color = Color.white;
    }

    //Store marked squares
    LastSquareFrom = (Squares)from;
    LastSquareTo = (Squares)to;

    //Since board was changed by computer update board
    UpdateBoard();
  }


  public void Undo() {

    //Calls the engine undo move
    UndoMove();

    //Reset color
    SquaresObj[(int)LastSquareFrom].gameObject.GetComponent<Image>().color = Color.white;
    SquaresObj[(int)LastSquareTo].gameObject.GetComponent<Image>().color = Color.white;

    //Sinde the board has changed update the move
    UpdateBoard();
  }
}
\$\endgroup\$
  • \$\begingroup\$ This is too broad to be answered here. It's not simply changing the sprites into 3D models. When dealing with 3D you add a new dimension and rendering 3D is different then 2D (for example: without lighting you won't see anything in a 3D world). \$\endgroup\$ – Madmenyo Feb 6 '17 at 9:13
  • \$\begingroup\$ There's the code [Serializable] public class PieceSet { public Sprite Pawn; public Sprite Bishop; public Sprite Knight; public Sprite Rook; public Sprite Queen; public Sprite King; public Sprite Square; } I want to make it to public GameObject and fix the other codes below but I don't know what to use in this part obj.GetComponent<Image>().sprite = WhitePieces.Square; //White square \$\endgroup\$ – Taneda Feb 6 '17 at 9:25
  • 1
    \$\begingroup\$ well do you have a 3d model you want to use? A sprite is a 2D image, like a picture you take on your camera. A 3d model is completely different... You cannot "convert" a sprite to a 3d model - So you will first need to acquire the 3d models you wish to use... \$\endgroup\$ – Milney Feb 6 '17 at 10:31
  • \$\begingroup\$ yes i got 3d models, all i want to do is convert the code by removing the sprites code in my source code. \$\endgroup\$ – Taneda Feb 6 '17 at 13:23
1
\$\begingroup\$

You currently have a very tight coupling between your game logic and your game visualization. Your CreatePiece method does literally nothing but change an image (the method name itself is in fact quite misleading. It doesn't create anything. It changes an "Empty space" into a "Black Rook space". So a better name would be ChangePiece)

A better architecture would be to have a separate prefab for every type of chess piece and then handle the pieces on the board as GameObjects which are Instantiated as children of the tiles when a new game is started, made a child of a different tile when a player makes a move and Destroyed when taken by an opponent piece. The nice thing about this architecture is that the game object prefabs control how they are displayed. They can have a SpriteRenderer component, a MeshRenderer, a TextRender or whatever. The part of your code architecture which handles the actual game mechanics doesn't care.

With this architecture you could also add a script to each prefab which implements the movement rules for that chess piece. When you move all piece-specific game mechanics into the piece-prefab, you can very easily add new kinds of pieces to the game (you don't really want to make the 165745345th simulation of classic FIDE chess without any form of new gameplay ideas at all, do you?).

But if you would like to stick with your architecture, then all you need to do is replace the SpriteRenderer on your tiles with a MeshRenderer and a MeshFilter. If you want to change the color of a piece, switch out the material of the MeshRenderer. If you want to change the type of a piece, change the Mesh (3d model) of the MeshFilter.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.