Files
JuegoSim/Assets/_Project/Scripts/Code/BlockExtensions/Concrete/ExistingBlockPlacementHandler.cs
T
2026-07-21 08:56:10 +03:00

80 lines
2.4 KiB
C#

using UnityEngine;
/// <summary>
/// Placement handler for repositioning an already-placed block.
/// </summary>
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<Block>().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<Renderer>())
{
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<Transform, bool> 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");
}
}