- Home /
Spawn after completion of drag and drop
I am a beginner at Unity and C# and I have started off by making pieces of games instead of whole games to understand how to make a whole game. I have accomplished making a simple drag and drop by mixing some tutorials and samples together with the following below:
using UnityEngine; using System.Collections; public class InputManager : MonoBehaviour
{ private bool draggingItem = false; private GameObject draggedObject; private Vector2 touchOffset;
void Update()
{
if (HasInput)
{
DragOrPickUp();
}
else
{
if (draggingItem)
DropItem();
}
}
Vector2 CurrentTouchPosition
{
get
{
Vector2 inputPos;
inputPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
return inputPos;
}
}
private void DragOrPickUp()
{
var inputPosition = CurrentTouchPosition;
if (draggingItem)
{
draggedObject.transform.position = inputPosition + touchOffset;
}
else
{
RaycastHit2D[] touches = Physics2D.RaycastAll(inputPosition, inputPosition, 0.5f);
if (touches.Length > 0)
{
var hit = touches[0];
if (hit.transform != null)
{
draggingItem = true;
draggedObject = hit.transform.gameObject;
touchOffset = (Vector2)hit.transform.position - inputPosition;
draggedObject.transform.localScale = new Vector3(1.2f, 1.2f, 1.2f);
}
}
}
}
private bool HasInput
{
get
{
// returns true if either the mouse button is down or at least one touch is felt on the screen
return Input.GetMouseButton(0);
}
}
void DropItem()
{
draggingItem = false;
draggedObject.transform.localScale = new Vector3(1f, 1f, 1f);
}
}
I was wondering how I would go about having there be only specific places where the drop of the drag and drop could be completed? So, if I had a 9x9 grid made of prefab squares with 2D colliders on them meant to act as a board, how would I ensure that the game piece that I am dragging can only ever fall onto one of these 9 game board tiles?
Your answer
