shmodot/scripts/Railway.cs

83 lines
1.9 KiB
C#
Raw Normal View History

2022-08-04 22:20:29 +02:00
using Godot;
using System;
2022-08-15 00:50:09 +02:00
[Tool]
2022-08-12 01:16:38 +02:00
public class Railway : Node
2022-08-04 22:20:29 +02:00
{
2022-08-15 00:50:09 +02:00
[Export]
private NodePath[] _railPaths;
[Export]
private NodePath _centreLine;
[Export]
private float _railWidth;
[Export]
private float _railHeight;
[Export]
private float _railGauge = 1.0f;
2022-08-12 01:16:38 +02:00
private Path _path = null;
private Path Path
2022-08-04 22:20:29 +02:00
{
2022-08-12 01:16:38 +02:00
get
{
if (_path == null)
{
2022-08-15 00:50:09 +02:00
_path = GetNode<Path>(_centreLine);
2022-08-12 01:16:38 +02:00
}
return _path;
}
2022-08-04 22:20:29 +02:00
}
2022-08-12 01:16:38 +02:00
public Curve3D Curve => Path.Curve;
2022-08-15 00:50:09 +02:00
// the centre line should not have geometry directly associated with it.
// instead, two additional path/csgpolygon combinations should be managed
// in reference to the centre line for the left and right rails.
2022-08-04 22:20:29 +02:00
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
}
2022-08-15 00:50:09 +02:00
private void SetRailCrossSection()
{
// error checkin
if (_railPaths.Length != 2)
throw new Exception("need 2 rails");
// set rail geometry
for (int i = 0; i < 2; i++)
{
var rail = GetNode<CSGPolygon>(_railPaths[i]);
float w = _railWidth;
float h = _railHeight;
// horizontal offset of rail from centreline
float c = (-.5f + i) * _railGauge;
var polygon = new Vector2[4];
polygon[0] = new Vector2(c - w, 0);
polygon[1] = new Vector2(c - w, h);
polygon[2] = new Vector2(c + w, h);
polygon[3] = new Vector2(c + w, 0);
rail.Polygon = polygon;
}
}
2022-08-04 22:20:29 +02:00
public override void _Process(float delta)
{
2022-08-15 00:50:09 +02:00
if (Engine.EditorHint)
{
SetRailCrossSection();
}
2022-08-12 01:16:38 +02:00
}
public void AddPathFollower(PathFollow pathFollow)
{
Path.AddChild(pathFollow);
2022-08-04 22:20:29 +02:00
}
}