- Home /
Drag and Drop "Puzzle" Game con't always work
HI! I'm making a Puzzle game in Unity 2D. I have a scene with nine colliders and I instantiate over them nine cards the will compose the puzzle. I have BoxColliders2D on every card. I have this script that is the logic of the game:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider2D))]
public class Drag : MonoBehaviour
{
public Collider2D[] table = new Collider2D[6];
private Vector3 screenSpace;
private Vector3 offset;
private bool atPlace;
private void Start()
{
table[0] = GameObject.Find("img1").GetComponent<Collider2D>();
table[1] = GameObject.Find("img2").GetComponent<Collider2D>();
table[2] = GameObject.Find("img3").GetComponent<Collider2D>();
table[3] = GameObject.Find("img4").GetComponent<Collider2D>();
table[4] = GameObject.Find("img5").GetComponent<Collider2D>();
table[5] = GameObject.Find("img6").GetComponent<Collider2D>();
atPlace = false;
}
void OnMouseDown()
{
this.GetComponent<SpriteRenderer>().sortingOrder = 10;
this.GetComponent<SpriteRenderer>().color = Color.red;
screenSpace = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
}
private void OnMouseUp()
{
this.GetComponent<SpriteRenderer>().color = Color.white;
if (!atPlace)
this.GetComponent<SpriteRenderer>().sortingOrder = 5;
else
this.GetComponent<SpriteRenderer>().sortingOrder = 4;
}
void OnMouseDrag()
{
Vector3 curScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset;
transform.position = curPosition;
for (int i = 0; i < table.Length; i++)
{
if (table[i].bounds.Contains(curPosition))
{
if (table[i].name + "(Clone)" == this.name)
{
Debug.Log(table[i].name + "(Clone)");
atPlace = true;
this.transform.position = table[i].transform.position;
this.GetComponent<Drag>().enabled = false;
this.GetComponent<BoxCollider2D>().enabled = false;
}
}
}
}
}
But sometimes it fails moving a card: the card is left fixed in this original position... The problem is sorted since the beginning of the construction of the script, in the OnMouseDown() and OnMouseDrag() functions...without the rest of the logic. Anyone has an idea to fix that error? Very Thanks in advice.
PS If I turn to "Scence" in runtime and I move the fixed card, in "Game" it return movable...
Your answer
Follow this Question
Related Questions
Dragging one object, but when it overlaps another it sticks also 0 Answers
Is there a way to add transition puzzle image in 2d sliding puzzle to another image once solved? 0 Answers
Unity 4.6: Drag and drop 1 Answer
Is there a way to make something not draggable 1 Answer
Jigsaw Puzzle Drag & Drop issues. 0 Answers