GodotComponentTest/scenes/HexTile3D.cs

110 lines
3.1 KiB
C#
Raw Normal View History

2022-12-03 21:58:28 +01:00
using Godot;
public class HexTile3D : Spatial
{
public enum TileType
{
Sand,
Grass,
DeepGrass
}
static public TileType[] ValidTileTypes = { TileType.Sand, TileType.Grass, TileType.DeepGrass };
// scene nodes
private MeshInstance _mesh;
private Area _area;
// signals
[Signal]
delegate void TileSelected(HexTile3D tile3d);
// other member variables
private SpatialMaterial _sandMaterial;
private SpatialMaterial _grassMaterial;
private SpatialMaterial _deepGrassMaterial;
private SpatialMaterial _previousMaterial;
public HexCell Cell = new HexCell();
public bool IsMouseOver = false;
private TileType _type;
public TileType Type
{
get
{
return _type;
}
set
{
_type = value;
switch (_type)
{
case TileType.Sand: _mesh.SetSurfaceMaterial(0, _sandMaterial);
break;
case TileType.Grass: _mesh.SetSurfaceMaterial(0, _grassMaterial);
break;
case TileType.DeepGrass: _mesh.SetSurfaceMaterial(0, _deepGrassMaterial);
break;
default:
GD.Print("Invalid tile type: " + value.ToString());
break;
}
}
}
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
_mesh = GetNode<MeshInstance>("Mesh");
_area = GetNode<Area>("Mesh/Area");
_area.Connect("input_event", this, nameof(OnAreaInputEvent));
_area.Connect("mouse_entered", this, nameof(OnAreaMouseEntered));
_area.Connect("mouse_exited", this, nameof(OnAreaMouseExited));
_sandMaterial = GD.Load<SpatialMaterial>("res://materials/SandTile.tres");
_grassMaterial = GD.Load<SpatialMaterial>("res://materials/GrassTile.tres");
_deepGrassMaterial = GD.Load<SpatialMaterial>("res://materials/DeepGrassTile.tres");
this.Type = TileType.Grass;
}
public void OnAreaInputEvent(Node camera, InputEvent inputEvent, Vector3 position, Vector3 normal, int shapeIndex)
{
if (IsMouseOver && inputEvent is InputEventMouseButton)
{
InputEventMouseButton mouseButtonEvent = (InputEventMouseButton)inputEvent;
if (mouseButtonEvent.ButtonIndex == 1 && mouseButtonEvent.Pressed)
{
EmitSignal("tile_selected", this);
}
}
}
public void OnAreaMouseEntered()
{
IsMouseOver = true;
_previousMaterial = (SpatialMaterial)_mesh.MaterialOverride;
SpatialMaterial clonedMaterial = (SpatialMaterial)_mesh.GetSurfaceMaterial(0).Duplicate();
clonedMaterial.AlbedoColor = new Color(1, 0, 0);
_mesh.MaterialOverride = clonedMaterial;
}
public void OnAreaMouseExited()
{
IsMouseOver = false;
_mesh.MaterialOverride = _previousMaterial;
}
// // Called every frame. 'delta' is the elapsed time since the previous frame.
// public override void _Process(float delta)
// {
//
// }
}