Hi all,
Just a quick run-down before I post the code, this is a 2D board game that revolves around allowing players to place as many board tokens on the board as they like, so just the gain a visual image there would be token types on the side of the game screen where players can drag and drop onto the board to create a copy of that token, they can create as many copies of any given token as many times as they like.
Right now I’m able to clone an object but no indefinitely (about once or twice) then the drag and drop function stops working for some odd reason (maybe something to do with the ray casting?), I’m pretty stumped on this one, hoping someone can help :).
Here’s the code:
var grabbed : Transform;
var grabDistance : float = 10.0f;
var grabLayerMask : int;
var grabOffset : Vector3;
var useToggleDrag : boolean;
var origPos : Vector3;
//reference to the prefab we instantiate on drop
var dropObject : Transform;
function Update ()
{
if (useToggleDrag)
{
UpdateToggleDrag();
}
else
{
UpdateHoldDrag();
}
}
// Toggles drag with mouse click
function UpdateToggleDrag ()
{
if (Input.GetMouseButtonDown(0))
{
Grab();
}
else
{
if (grabbed)
{
Drag();
}
}
}
// Drags when user holds down button
function UpdateHoldDrag ()
{
if (Input.GetMouseButton(0))
{
if (grabbed)
{
Drag();
} else {
Grab();
}
}
else
{
if(grabbed)
{
//restore the original layermask
grabbed.gameObject.layer = grabLayerMask;
}
grabbed = null;
}
}
function Grab()
{
if (grabbed)
{
grabbed = null;
}
else
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit))
{
grabbed = hit.transform;
if (grabbed.parent)
{
grabbed = grabbed.parent.transform;
}
//set the object to ignore raycasts
grabLayerMask = grabbed.gameObject.layer;
grabbed.gameObject.layer = 2;
//now immediately do another raycast to calculate the offset
if (Physics.Raycast(ray, hit))
{
grabOffset = grabbed.position - hit.point;
}
else
{
//important - clear the grab if there is nothing
//behind the object to drag against
grabbed = null;
}
}
}
}
function Drag()
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit))
{
grabbed.position = hit.point + grabOffset;
}
}
function OnMouseUp()
{
//instantiate new object
var newToken = Instantiate( dropObject, origPos, transform.rotation );
}
Thanks all.