You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Babushka/scripts/CSharp/Common/Farming/FarmingControls2D.cs

132 lines
3.7 KiB

using Godot;
using Godot.Collections;
namespace Babushka.scripts.CSharp.Common.Farming;
[GlobalClass]
public partial class FarmingControls2D : Node2D
{
[Export] private Sprite2D _hoeSprite;
[Export] private Sprite2D _wateringCanSprite;
[Export] private PackedScene _fieldPrefab;
[Export] private Node2D _movingPlayer;
[Export] private Camera2D _camera;
public FieldService2D FieldParent;
private int _toolId = -1;
#region Tools
/// <summary>
/// If no tool has been set, then set the current tool to the incoming tool id.
/// </summary>
/// <param name="toolId">The id of the tool to activate if possible</param>
/// <returns>If the tool in question was activated.</returns>
public bool TryActivateTool(int toolId)
{
bool activate;
//if our hands are empty, activate
if (_toolId == -1)
{
activate = true;
}
else
{
//if we're already carrying a tool, deactivate or fail return
if (_toolId == toolId)
{
activate = false;
}
else
{
return false;
}
}
switch (toolId)
{
case 0:
_hoeSprite.Visible = activate;
break;
case 1:
_wateringCanSprite.Visible = activate;
break;
default:
_toolId = -1;
break;
}
_toolId = activate ? toolId : -1;
return activate;
}
#endregion
public override void _Input(InputEvent @event)
{
Vector2 mousePosition = _camera.GetGlobalMousePosition();
Vector2I mousePositionInteger = (Vector2I) mousePosition;
Vector2I adjustedPosition = AdjustValue(mousePositionInteger, new Vector2I(735, 651));
if (@event.IsActionPressed("click") && _toolId == 0)
{
MakeField(adjustedPosition);
}
if (@event.IsActionPressed("click") && _toolId == 1)
{
WaterTheField(adjustedPosition);
}
}
private void WaterTheField(Vector2I fieldPosition)
{
FieldBehaviour2D field = FieldParent.Get(fieldPosition);
if (field == null)
return;
field.Water();
}
private void MakeField(Vector2I fieldPosition)
{
if(FieldParent == null || _fieldPrefab == null)
return;
// only try to instantiate a field if you're in the allowed area
if (!FieldParent.FieldAllowed())
return;
// only instantiate a field if there isn't one already.
if(FieldParent.Get(fieldPosition) == null)
{
Node fieldInstance = _fieldPrefab.Instantiate();
if (fieldInstance is Node2D field2d)
{
// add dictionary entry for the field
Array<Node> fields = field2d.FindChildren("*", nameof(FieldBehaviour2D));
if (fields.Count > 0)
FieldParent.TryAddEntry(fieldPosition, fields[0] as FieldBehaviour2D);
// reposition and reparent the instance
field2d.Position = new Vector2(fieldPosition.X, fieldPosition.Y);;
FieldParent.AddChild(fieldInstance);
}
}
}
private int AdjustValue(float value)
{
float adjustedValue = value / 500;
adjustedValue = Mathf.RoundToInt(adjustedValue);
adjustedValue *= 500;
return (int)adjustedValue;
}
private Vector2I AdjustValue(Vector2I input, Vector2I step)
{
return input.Snapped(step);
}
}