newlon/scripts/components/level/PlantField.cs

84 lines
2.8 KiB
C#

using Godot;
public partial class PlantField : Node2D
{
private Sprite2D _plantSetter;
private readonly Vector2 tile = new Vector2(Utility.TileWidth, Utility.TileHeight);
private PlantResource _resource;
private PlantSlot _slot;
private bool _previousCanPlace;
public override void _Ready()
{
LevelController.Instance.PlantField = this;
_plantSetter = GetChild<Sprite2D>(0);
}
public void SetPlant(PlantSlot slot, PlantResource plant)
{
_resource = plant;
_slot = slot;
}
public override void _Process(double delta)
{
// Getting and storing global mouse position, setting plant-poiner to it
var mouse_pos = GetGlobalMousePosition();
_plantSetter.GlobalPosition = mouse_pos;
// Getting position in grid coordinates
var expected_pos = (_plantSetter.GlobalPosition / tile).Ceil() * tile - new Vector2(20, 14);
// Checking for boundaries
bool inBoundary = expected_pos.X > Utility.LeftFieldBoundary.X && expected_pos.X < Utility.RightFieldBoundary.X && expected_pos.Y > Utility.LeftFieldBoundary.Y && expected_pos.Y < Utility.RightFieldBoundary.Y;
bool canPlace = _resource != null
&& inBoundary
&& LevelController.Instance.Pools.EntityField[_resource.Layer].ContainsKey(expected_pos) == false
&& LevelController.Instance.LevelData.CheckSpendSun(_resource.Cost);
// Setting visuals
if (_previousCanPlace != canPlace)
{
if (canPlace)
{
Material.Set("shader_parameter/amount", 0);
}
else
{
Material.Set("shader_parameter/amount", 1);
}
Cursor.Instance.plant = canPlace;
Cursor.Instance.UpdateCursor();
}
_previousCanPlace = canPlace;
if (canPlace)
_plantSetter.GlobalPosition = expected_pos;
_plantSetter.Texture = _resource == null ? null : _resource.Preview;
}
public override void _UnhandledInput(InputEvent @event)
{
if (@event.IsActionPressed("cancel_plant") && _slot != null)
{
_slot.ReleaseFocus();
}
if (@event.IsActionPressed("primary_action") && _previousCanPlace)
{
var plant = _resource.Scene.Instantiate<RuntimePlantData>();
LevelController.Instance.Pools.Plants.AddChild(plant);
plant.GlobalPosition = (_plantSetter.GlobalPosition / tile).Ceil() * tile - new Vector2(20, 14);
plant.Resource = _resource;
LevelController.Instance.Pools.EntityField[_resource.Layer].Add(plant.GlobalPosition, plant as IEntity);
LevelController.Instance.LevelData.SpendSun(_resource.Cost);
// Unfocusing and recharging slot
_slot.Recharge();
}
}
}