using UnityEngine;
///
/// Placement handler for repositioning an already-placed block.
///
public class ExistingBlockPlacementHandler : IPlacementHandler
{
private readonly CommandHandler _commandHandler;
public ExistingBlockPlacementHandler(CommandHandler commandHandler)
{
_commandHandler = commandHandler;
Debug.Log("initialize the ExistingBlockPlacement");
}
public void Commit(BlockEditContext ctx)
{
if (ctx.SourceObject == null) return;
_commandHandler.moveBlock(
ctx.SourceObject.GetComponent().getBlockId(),
ctx.OriginalPosition,
ctx.GhostTransform.position,
ctx.OriginalRotation,
ctx.GhostTransform.rotation);
// ensure the correct positionning after commiting
RestoreObject(ctx, ctx.GhostTransform.position, ctx.GhostTransform.rotation);
}
public void Cancel(BlockEditContext ctx)
{
if (ctx.SourceObject == null) return;
RestoreObject(ctx, ctx.OriginalPosition, ctx.OriginalRotation);
}
private void RestoreObject(BlockEditContext ctx, Vector3 pos, Quaternion rot)
{
ctx.SourceObject.transform.SetPositionAndRotation(pos, rot);
RestoreMaterialAlphaAndColor(ctx.SourceObject);
SetLayerRecursively(ctx.SourceObject, LayerMask.NameToLayer("Interactable"));
ctx.SourceObject.SetActive(true);
}
private void RestoreMaterialAlphaAndColor(GameObject obj)
{
foreach (var r in obj.GetComponentsInChildren())
{
if (r.gameObject.layer == LayerMask.NameToLayer("Gizmos")) continue;
foreach (var mat in r.materials)
{
if (mat.HasProperty("_Color"))
{
mat.color = new Color(1f, 1f, 1f, 1f);
}
}
}
}
private void SetLayerRecursively(GameObject obj, int layer, System.Func Method)
{
if (Method(obj.transform))
obj.layer = layer;
foreach (Transform child in obj.transform)
SetLayerRecursively(child.gameObject, layer, Method);
}
private void SetLayerRecursively(GameObject obj, int layer)
{
SetLayerRecursively(obj, layer, x =>
{
return x.gameObject.layer != LayerMask.NameToLayer("Gizmos");
});
}
public void Debugln()
{
Debug.Log("Hi I'm Existing");
}
}