I am making a 2D chess game and I ran into a problem I think with layering/colliders between sprites. For now my game is doing two things:
- Instantiating from code 64 sprites that are square tiles to match typical chessboard appearance.
- Instantiating from code 32 sprites that are chess pieces. They are arranged to match starting chess position.
Instantiated sprites are cloned from its prefab and their properties like color, type of piece or position are adjusted during instantiation. Square prefab has BoxCollider2D and its Order in Layer is set to 0, while Piece prefab has also BoxCollider2D but its Order in Layer is set to 1. When instantiated, the 'z' position of both of them is set during instantiation accordingly to value of its Order in Layer (0 and 1). Both of them are in layer 'Default' - I didn't changed anything here. All of it of course to ensure that pieces will spawn and render on top of squares.
Then I wrote a simple draggable script that is catching mouse position and modifies the position of object according to it, using OnMouseDown() and OnMouseDrag() functions. The script is attached to the Piece prefab.
My problems:
- The drag & drop works only if the piece doesn't have a square sprite underneath it.
- This functionality works flawlessly if I uncheck BoxCollider2D from squares.
- If I attach draggable script to squares also (for debugging reasons), when I try to move a sprite it ALWAYS moves the square first, not the piece.
- I debugged OnMouseDown() & OnMouseDrag() functions and they just don't work if piece is rendered on top of square.
I assume something is wrong with layering or colliders between pieces and squares.
- How can I fix this problem to be sure that I can always move the piece that is rendered on square while NOT removing box colliders from squares?
- Assuming that my next goal is to change that 'free' move to locking it to the position of squares - how can I extend my script to do this? I suppose box colliders from squares will be key thing, so I don't want remove it to fix my 1st problem.
Here is the draggable script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Draggable : MonoBehaviour {
Vector3 offset;
void OnMouseDown() {
offset = transform.position - MouseWorldPosition();
}
void OnMouseDrag() {
transform.position = MouseWorldPosition() + offset;
}
void OnMouseUp() {
Debug.Log("OnMouseUp");
}
Vector3 MouseWorldPosition() {
var mouseScreenPos = Input.mousePosition;
mouseScreenPos.z = Camera.main.WorldToScreenPoint(transform.position).z;
return Camera.main.ScreenToWorldPoint(mouseScreenPos);
}
}
There are some shenanigans also in my scripts (mostly about instantiating) but I believe they are not fundamental to that problem to mention them. Thank you from your help!