Ship Locomotion & Tech Tree Panel

Ship locomotion now accounts for tangential velocity, slows down properly with terminal phase separated into velocity matching behavior
Tech tree properties panel visualizes parents and children correctly
This commit is contained in:
hyperion51 2020-04-25 00:01:13 +01:00
commit b589a6422c
25 changed files with 1073 additions and 760 deletions

View file

@ -13,8 +13,17 @@ public class AgentController
public ZoneData Zone { get; set; }
private Locomotion _locomotion;
private VelocityMatch _velocityMatch;
private Random _random = new Random((uint) (DateTime.Now.Ticks%uint.MaxValue));
private float _stoppingTime;
private float _stoppingDistance;
private float _turnaroundDistance;
private float _turnaroundTime;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private KeyValuePair<DatabaseEntry, Entity> _objective;
private float _velocityLimit;
public AgentController(GameContext context, ZoneData zone, Entity entity)
{
Entity = entity;
@ -22,22 +31,50 @@ public class AgentController
Context = context;
EntityAgent = new EntityAgent(context, zone, entity);
_locomotion = new Locomotion(entity);
_velocityMatch = new VelocityMatch(entity);
_velocityMatch.OnMatch += () =>
{
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
};
EntityAgent.CurrentBehavior = _locomotion;
RandomTarget();
_thrust = entity.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entity.Axes.Keys.FirstOrDefault(x => x is Turning);
var velocityLimitData = entity.GetBehaviorData<VelocityLimitData>().FirstOrDefault();
_velocityLimit = Context.Evaluate(velocityLimitData.TopSpeed, entity.Hull, entity);
_stoppingTime = _velocityLimit / Context.Evaluate((_thrust.Data as ThrusterData).Thrust, _thrust.Item, Entity) * Entity.Mass;
_stoppingDistance = _stoppingTime * _velocityLimit / 2;
_turnaroundTime = PI / Context.Evaluate((_turning.Data as TurningData).Torque, _turning.Item, entity) * entity.Mass;
_turnaroundDistance = _turnaroundTime * _velocityLimit;
_locomotion.LeadTime = _stoppingTime;
}
public void Update(float delta)
{
EntityAgent.Update(delta);
var distance = length(_locomotion.Objective.Position - Entity.Position);
Context.Log($"Agent Distance: {distance}");
if(distance < 20)
RandomTarget();
Context.Log(
$"Agent Mode: {EntityAgent.CurrentBehavior.GetType()} " +
$"Agent Distance: {distance} " +
$"Turnaround Distance: {_stoppingDistance + _turnaroundDistance} " +
$"Objective: {_objective.Key.ID.ToString().Substring(0, 8)}");
if (EntityAgent.CurrentBehavior == _locomotion)
{
var velocity = length(Entity.Velocity);
_stoppingTime = velocity / Context.Evaluate((_thrust.Data as ThrusterData).Thrust, _thrust.Item, Entity) * Entity.Mass;
_stoppingDistance = _stoppingTime * velocity / 2;
if (distance < _stoppingDistance + _turnaroundDistance)
EntityAgent.CurrentBehavior = _velocityMatch;
_velocityMatch.Objective = _locomotion.Objective;
}
}
private void RandomTarget()
{
var entities = Context.ZoneEntities(Zone).ToArray();
_locomotion.Objective = entities[_random.NextInt(entities.Length)];
var entities = Context.ZoneContents[Zone].ToArray();
_objective = entities[_random.NextInt(entities.Length)];
_locomotion.Objective = _objective.Value;
}
}

View file

@ -7,10 +7,12 @@ using static Unity.Mathematics.math;
public class Locomotion : AgentBehavior
{
public Entity Objective;
public float LeadTime;
private Entity _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private const float Sensitivity = 1;
private const float TangentSensitivity = 2;
public Locomotion(Entity entity)
{
@ -23,13 +25,9 @@ public class Locomotion : AgentBehavior
{
if (Objective != null && _thrust != null && _turning != null)
{
float2 diff = Objective.Position - _entity.Position;
var directionAngle = atan2(diff.y, diff.x) / PI;
var currentAngle = atan2(_entity.Direction.y, _entity.Direction.x) / PI;
var d1 = directionAngle - currentAngle;
var d2 = directionAngle - 2 - currentAngle;
var d3 = directionAngle + 2 - currentAngle;
var angleDiff = abs(d1) < abs(d2) ? abs(d1) < abs(d3) ? d1 : d3 : abs(d2) < abs(d3) ? d2 : d3;
float2 diff = Objective.Position + Objective.Velocity * LeadTime - _entity.Position;
float2 tangential = _entity.Velocity - dot(normalize(diff), normalize(_entity.Velocity)) * _entity.Velocity;
float angleDiff = _entity.Direction.AngleDiff(normalize(diff) - tangential * TangentSensitivity);
_entity.Axes[_turning] = clamp(-angleDiff * Sensitivity, -1, 1);
_entity.Axes[_thrust] = 1;
}

View file

@ -0,0 +1,38 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class VelocityMatch : AgentBehavior
{
public event Action OnMatch;
public Entity Objective;
private Entity _entity;
private IAnalogBehavior _thrust;
private IAnalogBehavior _turning;
private const float TurningSensitivity = 1;
private const float ThrustSensitivity = 1;
private const float TargetThreshold = .1f;
public VelocityMatch(Entity entity)
{
_entity = entity;
_thrust = entity.Axes.Keys.FirstOrDefault(x => x is Thruster);
_turning = entity.Axes.Keys.FirstOrDefault(x => x is Turning);
}
public override void Update(float delta)
{
if (Objective != null && _thrust != null && _turning != null)
{
var deltaV = Objective.Velocity - _entity.Velocity;
if(length(deltaV) < TargetThreshold)
OnMatch?.Invoke();
var angleDiff = _entity.Direction.AngleDiff(deltaV);
_entity.Axes[_turning] = clamp(-angleDiff * TurningSensitivity, -1, 1);
_entity.Axes[_thrust] = saturate(length(pow(saturate(dot(normalize(_entity.Direction),normalize(deltaV))), 8)*length(deltaV))*ThrustSensitivity);
}
}
}

View file

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df5185d5435658841878b6a8c9ff693b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View file

@ -52,7 +52,7 @@ public class Turning : IAnalogBehavior
public void Update(float delta)
{
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_turning * Context.Evaluate(_data.Torque, Item, Entity) * delta));
Entity.Direction = mul(Entity.Direction, Unity.Mathematics.float2x2.Rotate(_turning * Context.Evaluate(_data.Torque, Item, Entity) / Entity.Mass * delta));
Entity.AddHeat(abs(_turning) * Context.Evaluate(_data.Heat, Item, Entity) * delta);
Entity.VisibilitySources[this] = abs(_turning) * Context.Evaluate(_data.Visibility, Item, Entity);
}

View file

@ -39,5 +39,8 @@ public class VelocityLimit : IBehavior
public void Update(float delta)
{
var limit = Context.Evaluate(_data.TopSpeed, Item, Entity);
if (length(Entity.Velocity) > limit)
Entity.Velocity = normalize(Entity.Velocity) * limit;
}
}

View file

@ -23,7 +23,7 @@ public class Entity
protected readonly List<Gear> Items;
protected readonly List<ItemInstance> Cargo;
protected Gear Hull;
public Gear Hull { get; }
public float Mass { get; private set; }
public float SpecificHeat { get; private set; }
@ -44,8 +44,10 @@ public class Entity
SpecificHeat = (hull?.HeatCapacity ?? 0) +
Items.Sum(i => i.HeatCapacity) +
Cargo.Sum(ii => ii.HeatCapacity);
var activeItems = hull == null ? Items : Items.Append(hull);
Behaviors = Items
Behaviors = activeItems
.Where(i=>i.ItemData.Behaviors?.Any()??false)
.SelectMany(i => i.ItemData.Behaviors
.Select(bd => bd.CreateInstance(Context, this, i)))

View file

@ -220,6 +220,16 @@ public static class Extensions
return t * (t * (a * t + b) + c) + d;
}
public static float AngleDiff(this float2 a, float2 b)
{
var directionAngle = atan2(b.y, b.x) / PI;
var currentAngle = atan2(a.y, a.x) / PI;
var d1 = directionAngle - currentAngle;
var d2 = directionAngle - 2 - currentAngle;
var d3 = directionAngle + 2 - currentAngle;
return abs(d1) < abs(d2) ? abs(d1) < abs(d3) ? d1 : d3 : abs(d2) < abs(d3) ? d2 : d3;
}
}
// https://github.com/Burtsev-Alexey/net-object-deep-copy

View file

@ -200,6 +200,9 @@ public class StrategyGameManager : MonoBehaviour
{
ship.Value.transform.position = float3(ship.Key.Position * ZoneSizeScale, .05f);
ship.Value.Icon.transform.up = (Vector2) ship.Key.Direction;
var thrusterScale = ship.Value.Thruster.localScale;
thrusterScale.x = ship.Key.Axes.First(kvp => kvp.Key is Thruster).Value;
ship.Value.Thruster.localScale = thrusterScale;
}
}
}

View file

@ -29,13 +29,16 @@ public class TechTreeMsagl : MonoBehaviour
public TextMeshProUGUI ProductionTime;
public TextMeshProUGUI Produces;
public TextMeshProUGUI ResearchTime;
public Prototype RequirementPrototype;
public Prototype DependencyPrototype;
public Prototype DescendantPrototype;
public RectTransform RequirementParent;
public RectTransform DependencyParent;
public RectTransform DescendantParent;
public RectTransform RequirementPrefab;
public RectTransform DependencyPrefab;
public RectTransform DescendantPrefab;
public ClickRaycaster ClickRaycaster;
[Section("Graph Generation")]
public bool TestMode = false;
public bool TestMode;
public int TechCount = 50;
public int SeedTechs = 5;
public int RollingWindowSize = 50;
@ -83,7 +86,7 @@ public class TechTreeMsagl : MonoBehaviour
private List<Prototype> _linkInstances = new List<Prototype>();
private List<Prototype> _arrowInstances = new List<Prototype>();
private Texture2D[] _icons;
private List<Prototype> _propertyInstances = new List<Prototype>();
private List<RectTransform> _propertyInstances = new List<RectTransform>();
public BlueprintData[] Blueprints { get; set; }
@ -341,7 +344,8 @@ public class TechTreeMsagl : MonoBehaviour
if (!TestMode)
tech.Fill.GetComponent<ClickableCollider>().OnClick += (collider, data) =>
{
foreach (var instance in _propertyInstances) instance.ReturnToPool();
foreach (var instance in _propertyInstances) Destroy(instance.gameObject);
_propertyInstances.Clear();
var blueprint = (BlueprintData) vertex.UserData;
PropertiesPanel.gameObject.SetActive(true);
TechName.text = blueprint.Name;
@ -352,20 +356,21 @@ public class TechTreeMsagl : MonoBehaviour
foreach (var ingredient in blueprint.Ingredients)
{
var ingredientData = Context.Cache.Get<ItemData>(ingredient.Key);
var ingredientInstance = RequirementPrototype.Instantiate<Prototype>();
var ingredientInstance = Instantiate(RequirementPrefab, RequirementParent);
ingredientInstance.GetComponentInChildren<TextMeshProUGUI>().text = $"{ingredient.Value} {ingredientData.Name}";
_propertyInstances.Add(ingredientInstance);
}
foreach (var dependency in blueprint.Dependencies)
{
var dependencyBlueprint = Context.Cache.Get<BlueprintData>(dependency);
var dependencyInstance = DependencyPrototype.Instantiate<Prototype>();
var dependencyInstance = Instantiate(DependencyPrefab, DependencyParent);
dependencyInstance.GetComponentInChildren<TextMeshProUGUI>().text = dependencyBlueprint.Name;
_propertyInstances.Add(dependencyInstance);
}
foreach (var descendant in graph.Edges.Where(e=>e.Source==vertex).Select(e=>(BlueprintData) e.Target.UserData))
foreach (var descendant in Blueprints.Where(bp =>
bp.Dependencies.Any(dep => blueprint.ID == dep)))
{
var descendantInstance = DescendantPrototype.Instantiate<Prototype>();
var descendantInstance = Instantiate(DescendantPrefab, DescendantParent);
descendantInstance.GetComponentInChildren<TextMeshProUGUI>().text = descendant.Name;
_propertyInstances.Add(descendantInstance);
}

View file

@ -5,15 +5,18 @@ using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ClickCatcher : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
public class ClickCatcher : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, /*IPointerUpHandler, IPointerDownHandler,*/ IPointerClickHandler
{
//public bool EnableMouse => PointerIsInside && !_catching;
public bool PointerIsInside { get; private set; }
public float ClickTime = .5f;
public event Action<PointerEventData> OnEnter;
public event Action<PointerEventData> OnExit;
public event Action<PointerEventData> OnClick;
private float downTime;
public static ClickCatcher Background
{
get
@ -40,6 +43,17 @@ public class ClickCatcher : MonoBehaviour, IPointerEnterHandler, IPointerExitHan
PointerIsInside = false;
}
// public void OnPointerUp(PointerEventData eventData)
// {
// if(Time.time - downTime < ClickTime)
// OnClick?.Invoke(eventData);
// }
//
// public void OnPointerDown(PointerEventData eventData)
// {
// downTime = Time.time;
// }
public void OnPointerClick(PointerEventData eventData)
{
OnClick?.Invoke(eventData);

View file

@ -21,8 +21,8 @@ public class ClickRaycaster : MonoBehaviour
var clickable = hit.collider.GetComponent<ClickableCollider>();
if (clickable != null)
clickable.Click(pointer);
else OnClickMiss?.Invoke();
}
else OnClickMiss?.Invoke();
};
}
}

View file

@ -8,4 +8,5 @@ public class ZoneShip : MonoBehaviour
public MeshRenderer Icon;
public TextMeshPro Label;
public Transform Thruster;
}