AI State Machine First Pass

Implemented first pass on code-driven state machine logic for flexible AI agents
This commit is contained in:
Reinier Vens 2021-02-11 03:14:20 +00:00
commit 8d4bd04891
26 changed files with 489 additions and 137 deletions

View file

@ -3,7 +3,7 @@ using System.Collections.Generic;
using Unity.Mathematics;
using static Unity.Mathematics.math;
public class AetheriaMath
public static class AetheriaMath
{
//first-order intercept using absolute target position
public static float3 FirstOrderIntercept

View file

@ -2,10 +2,15 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using RethinkDb.Driver.Ast;
using UniRx;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using float2 = Unity.Mathematics.float2;
public abstract class AgentBehavior
{
@ -32,3 +37,167 @@ public abstract class AgentBehavior
ControllerData = controllerData;
}
}
public class Agent
{
private BaseState _rootState;
private BaseState _currentState;
private Dictionary<BaseState, List<StateTransition>> _stateTransitions = new Dictionary<BaseState, List<StateTransition>>();
public AgentTask Task { get; set; }
public Ship Ship { get; }
public ItemManager ItemManager { get; }
public GameplaySettings Settings { get; }
public Agent(Ship ship)
{
Ship = ship;
ItemManager = Ship.ItemManager;
Settings = Ship.ItemManager.GameplaySettings;
_rootState = _currentState = new BaseState(this);
var patrolState = new PatrolOrbitsState(this);
AddTransition(_rootState, patrolState,
() => Task is PatrolOrbitsTask,
() => patrolState.Task = Task as PatrolOrbitsTask);
var patrolMoveState = new MoveToOrbitState(this);
AddTransition(patrolState, patrolMoveState,
() => true,
() => patrolMoveState.Orbit = patrolState.CurrentTarget);
AddTransition(patrolMoveState, patrolState,
() => patrolMoveState.Distance < 10,
() => patrolState.NextTarget());
}
public void AddTransition(BaseState source, BaseState targetState, Func<bool> condition, Action onTransition = null)
{
if(!_stateTransitions.ContainsKey(source))
_stateTransitions[source] = new List<StateTransition>();
_stateTransitions[source].Add(new StateTransition(targetState, condition, onTransition));
}
public void Transition(BaseState targetState, Action onTransition = null)
{
_currentState.OnExitState();
_currentState = targetState;
onTransition?.Invoke();
_currentState.OnEnterState();
}
public void Update(float delta)
{
_currentState.Update(delta);
foreach (var transition in _stateTransitions[_currentState])
if (transition.Condition())
{
Transition(transition.TargetState, transition.OnTransition);
break;
}
}
public class StateTransition
{
public StateTransition(BaseState targetState, Func<bool> condition, Action onTransition)
{
TargetState = targetState;
Condition = condition;
OnTransition = onTransition;
}
public BaseState TargetState { get; }
public Func<bool> Condition { get; }
public Action OnTransition { get; }
}
}
public class BaseState
{
protected Agent _agent;
public BaseState(Agent agent)
{
_agent = agent;
}
public virtual void Update(float delta){}
public virtual void OnEnterState(){}
public virtual void OnExitState(){}
}
public abstract class MoveToState : BaseState
{
private const float FORWARD_DELTA_THRESHOLD = 20;
private const float THRUST_DELTA_THRESHOLD = 1;
private VelocityLimit _velocityLimit;
protected abstract float2 TargetPosition { get; }
public float Distance { get; private set; }
protected MoveToState(Agent agent) : base(agent)
{
_velocityLimit = agent.Ship.GetBehavior<VelocityLimit>();
}
public override void Update(float delta)
{
var diff = TargetPosition - _agent.Ship.Position.xz;
var dir = normalize(diff);
Distance = length(diff);
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 100;
var desiredVelocity = dir * topSpeed;
var deltaV = desiredVelocity - _agent.Ship.Velocity;
var deltaVMag = length(deltaV);
var deltaVDirection = normalize(deltaV);
// If Delta V is above the threshold, direct the ship towards the delta and use only main thrusters
if (deltaVMag > FORWARD_DELTA_THRESHOLD)
{
_agent.Ship.LookDirection = float3(deltaVDirection.x, 0, deltaVDirection.y);
_agent.Ship.MovementDirection = float2(0, pow(dot(_agent.Ship.Direction, deltaVDirection), 2));
}
// If Delta V is low, direct the ship towards the target and use all thrusters
else if(deltaVMag > THRUST_DELTA_THRESHOLD)
{
var right = _agent.Ship.Direction.Rotate(ItemRotation.Clockwise);
_agent.Ship.LookDirection = float3(dir.x, 0, dir.y);
_agent.Ship.MovementDirection = float2(dot(right, deltaVDirection), dot(_agent.Ship.Direction, deltaVDirection));
}
else
{
_agent.Ship.LookDirection = float3(dir.x, 0, dir.y);
_agent.Ship.MovementDirection = float2.zero;
}
}
}
public class MoveToEntityState : MoveToState
{
public Entity TargetEntity { get; set; }
protected override float2 TargetPosition => TargetEntity?.Position.xz ?? float2.zero;
public MoveToEntityState(Agent agent) : base(agent) { }
}
public class MoveToOrbitState : MoveToState
{
public Guid Orbit { get; set; }
public MoveToOrbitState(Agent agent) : base(agent) { }
protected override float2 TargetPosition => _agent.Ship.Zone.GetOrbitPosition(Orbit);
}
public class PatrolOrbitsState : BaseState
{
public PatrolOrbitsTask Task;
public Guid CurrentTarget
{
get => Task.Circuit[_currentTargetIndex];
}
private int _currentTargetIndex;
public void NextTarget()
{
_currentTargetIndex++;
_currentTargetIndex %= Task.Circuit.Length;
}
public PatrolOrbitsState(Agent agent) : base(agent) { }
}

View file

@ -39,3 +39,9 @@ public enum TaskType
Attack,
Explore
}
public class PatrolOrbitsTask : AgentTask
{
public override TaskType Type => TaskType.Defend;
public Guid[] Circuit;
}

View file

@ -32,7 +32,7 @@ public class Locomotion : AgentBehavior
var diff = Objective - Entity.Position.xz;
// We want to go top speed in the direction of our target
var topSpeed = _velocityLimit?.Limit ?? 1000;
var topSpeed = _velocityLimit?.Limit ?? 100;
float2 desiredVelocity = normalize(diff) * topSpeed;
var accelerationTime = length(desiredVelocity - Entity.Velocity) / (_thrust / Entity.Mass);

View file

@ -9,40 +9,40 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class ChargedWeaponData : InstantWeaponData
{
[InspectableField, JsonProperty("chargeTime"), Key(19), RuntimeInspectable]
[InspectableField, JsonProperty("chargeTime"), Key(21), RuntimeInspectable]
public PerformanceStat ChargeTime = new PerformanceStat();
[InspectableField, JsonProperty("chargeEnergy"), Key(20), RuntimeInspectable]
[InspectableField, JsonProperty("chargeEnergy"), Key(22), RuntimeInspectable]
public PerformanceStat ChargeEnergy = new PerformanceStat();
[InspectableField, JsonProperty("chargeHeat"), Key(21), RuntimeInspectable]
[InspectableField, JsonProperty("chargeHeat"), Key(23), RuntimeInspectable]
public PerformanceStat ChargeHeat = new PerformanceStat();
[InspectableField, JsonProperty("canFireEarly"), Key(22)]
[InspectableField, JsonProperty("canFireEarly"), Key(24)]
public bool CanFireEarly;
[InspectableField, JsonProperty("failureCharge"), Key(23)]
[InspectableField, JsonProperty("failureCharge"), Key(25)]
public float FailureCharge;
[InspectableField, JsonProperty("failureDamage"), Key(24)]
[InspectableField, JsonProperty("failureDamage"), Key(26)]
public float FailureDamage = 1;
[InspectableField, JsonProperty("chargeDamage"), Key(25)]
[InspectableField, JsonProperty("chargeDamage"), Key(27)]
public float ChargeFiringDamageMultiplier = 1;
[InspectableField, JsonProperty("chargeSpread"), Key(26)]
[InspectableField, JsonProperty("chargeSpread"), Key(28)]
public float ChargeFiringSpreadMultiplier = 1;
[InspectableField, JsonProperty("chargeBurstCount"), Key(27)]
[InspectableField, JsonProperty("chargeBurstCount"), Key(29)]
public float ChargeFiringBurstCountMultiplier = 1;
[InspectableField, JsonProperty("chargeVisibility"), Key(28)]
[InspectableField, JsonProperty("chargeVisibility"), Key(30)]
public float ChargeFiringVisibilityMultiplier = 1;
[InspectableField, JsonProperty("chargeVelocity"), Key(29)]
[InspectableField, JsonProperty("chargeVelocity"), Key(31)]
public float ChargeFiringVelocityMultiplier = 1;
[InspectableField, JsonProperty("chargeHeatMul"), Key(30)]
[InspectableField, JsonProperty("chargeHeatMul"), Key(32)]
public float ChargeFiringHeatMultiplier = 1;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -131,7 +131,7 @@ public class ChargedWeapon : InstantWeapon
public override void Activate()
{
if(!_coolingDown)
if(!_charging && !_coolingDown)
{
OnStartCharging?.Invoke();
_charging = true;

View file

@ -11,7 +11,7 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class ConstantWeaponData : WeaponData
{
[InspectablePrefab, JsonProperty("ammoInterval"), Key(15)]
[InspectablePrefab, JsonProperty("ammoInterval"), Key(17)]
public float AmmoInterval = 1;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -112,7 +112,7 @@ public class ConstantWeapon : Weapon, IProgressBehavior
public override void Activate()
{
if(!_reloading)
if(!_firing && !_reloading)
{
_firing = true;
OnStartFiring?.Invoke();

View file

@ -9,16 +9,16 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class InstantWeaponData : WeaponData
{
[InspectableField, JsonProperty("count"), Key(15)]
[InspectableField, JsonProperty("count"), Key(17)]
public PerformanceStat Count = new PerformanceStat();
[InspectableField, JsonProperty("burstTime"), Key(16)]
[InspectableField, JsonProperty("burstTime"), Key(18)]
public PerformanceStat BurstTime = new PerformanceStat();
[InspectableField, JsonProperty("cooldown"), Key(17), RuntimeInspectable]
[InspectableField, JsonProperty("cooldown"), Key(19), RuntimeInspectable]
public PerformanceStat Cooldown = new PerformanceStat();
[InspectablePrefab, JsonProperty("ammoInterval"), Key(18)]
[InspectablePrefab, JsonProperty("ammoInterval"), Key(20)]
public bool SingleAmmoBurst;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -9,22 +9,22 @@ using Unity.Mathematics;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class LauncherData : LockWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(24)]
[InspectableAnimationCurve, JsonProperty("guidance"), Key(26)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(25)]
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(27)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(26)]
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(28)]
public float4[] LiftCurve;
[InspectableField, JsonProperty("thrust"), Key(27)]
[InspectableField, JsonProperty("thrust"), Key(29)]
public PerformanceStat Thrust = new PerformanceStat();
[InspectableField, JsonProperty("frequency"), Key(28)]
[InspectableField, JsonProperty("frequency"), Key(30)]
public float DodgeFrequency;
[InspectableField, JsonProperty("missileSpeed"), Key(29), RuntimeInspectable]
[InspectableField, JsonProperty("missileSpeed"), Key(31), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
@ -36,22 +36,22 @@ public class LauncherData : LockWeaponData
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn)]
public class GuidedWeaponData : InstantWeaponData
{
[InspectableAnimationCurve, JsonProperty("guidance"), Key(24)]
[InspectableAnimationCurve, JsonProperty("guidance"), Key(21)]
public float4[] GuidanceCurve;
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(25)]
[InspectableAnimationCurve, JsonProperty("thrustCurve"), Key(22)]
public float4[] ThrustCurve;
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(26)]
[InspectableAnimationCurve, JsonProperty("liftCurve"), Key(23)]
public float4[] LiftCurve;
[InspectableField, JsonProperty("thrust"), Key(27)]
[InspectableField, JsonProperty("thrust"), Key(24)]
public PerformanceStat Thrust = new PerformanceStat();
[InspectableField, JsonProperty("frequency"), Key(28)]
[InspectableField, JsonProperty("frequency"), Key(25)]
public float DodgeFrequency;
[InspectableField, JsonProperty("missileSpeed"), Key(29), RuntimeInspectable]
[InspectableField, JsonProperty("missileSpeed"), Key(26), RuntimeInspectable]
public PerformanceStat MissileVelocity = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -9,19 +9,19 @@ using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class LockWeaponData : InstantWeaponData
{
[InspectableField, JsonProperty("speed"), Key(19), RuntimeInspectable]
[InspectableField, JsonProperty("speed"), Key(21), RuntimeInspectable]
public PerformanceStat LockSpeed = new PerformanceStat();
[InspectableField, JsonProperty("sensorImpact"), Key(20)]
[InspectableField, JsonProperty("sensorImpact"), Key(22)]
public PerformanceStat SensorImpact = new PerformanceStat();
[InspectableField, JsonProperty("threshold"), Key(21), RuntimeInspectable]
[InspectableField, JsonProperty("threshold"), Key(23), RuntimeInspectable]
public PerformanceStat LockAngle = new PerformanceStat();
[InspectableField, JsonProperty("directionImpact"), Key(22)]
[InspectableField, JsonProperty("directionImpact"), Key(24)]
public PerformanceStat DirectionImpact = new PerformanceStat();
[InspectableField, JsonProperty("decay"), Key(23)]
[InspectableField, JsonProperty("decay"), Key(25)]
public PerformanceStat Decay = new PerformanceStat();
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)

View file

@ -4,12 +4,17 @@
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
using static Unity.Mathematics.math;
[InspectableField, MessagePackObject, JsonObject(MemberSerialization.OptIn), RuntimeInspectable]
public class SensorData : BehaviorData
{
[InspectableField, JsonProperty("sensitivity"), Key(3), RuntimeInspectable]
public PerformanceStat Sensitivity = new PerformanceStat();
[InspectableField, JsonProperty("sensitivityCurve"), Key(4), RuntimeInspectable]
public float4[] SensitivityCurve;
public override IBehavior CreateInstance(ItemManager context, Entity entity, EquippedItem item)
{
@ -38,6 +43,21 @@ public class Sensor : IBehavior
public bool Execute(float delta)
{
// TODO: Handle Active Detection / Visibility From Reflected Radiance
var hardpoint = Entity.Hardpoints[Item.Position.x, Item.Position.y];
var forward = Entity.HardpointTransforms.ContainsKey(hardpoint) ?
normalize(Entity.HardpointTransforms[hardpoint].direction.xz) :
Entity.Direction;
foreach (var entity in Entity.Zone.Entities)
{
var diff = entity.Position.xz - Entity.Position.xz;
var angle = acos(dot(forward, normalize(diff)));
var dist = length(diff);
Entity.EntityInfoGathered[entity] +=
entity.Visibility *
Context.Evaluate(_data.Sensitivity, Item.EquippableItem, Entity) *
_data.SensitivityCurve.Evaluate(angle / PI) *
delta / dist;
}
return true;
// var ship = Hardpoint.Ship.Ship.transform;
// var contacts =

View file

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using MessagePack;
using Newtonsoft.Json;
using Unity.Mathematics;
[Union(0, typeof(InstantWeaponData)),
Union(1, typeof(LauncherData)),
@ -27,34 +28,40 @@ public abstract class WeaponData : BehaviorData
[RangedFloatInspectable(0,1), JsonProperty("damageSpread"), Key(4)]
public PerformanceStat DamageSpread = new PerformanceStat();
[InspectableField, JsonProperty("range"), Key(5), RuntimeInspectable]
[InspectableField, JsonProperty("minRange"), Key(5), RuntimeInspectable]
public PerformanceStat MinRange = new PerformanceStat();
[InspectableField, JsonProperty("range"), Key(6), RuntimeInspectable]
public PerformanceStat Range = new PerformanceStat();
[InspectableAnimationCurve, JsonProperty("damageRange"), Key(7), RuntimeInspectable]
public float4[] DamageCurve;
[InspectablePrefab, JsonProperty("effect"), Key(6)]
[InspectablePrefab, JsonProperty("effect"), Key(8)]
public string EffectPrefab;
[InspectablePrefab, JsonProperty("energy"), Key(7), RuntimeInspectable]
[InspectablePrefab, JsonProperty("energy"), Key(9), RuntimeInspectable]
public PerformanceStat Energy = new PerformanceStat();
[InspectablePrefab, JsonProperty("heat"), Key(8), RuntimeInspectable]
[InspectablePrefab, JsonProperty("heat"), Key(10), RuntimeInspectable]
public PerformanceStat Heat = new PerformanceStat();
[InspectablePrefab, JsonProperty("visibility"), Key(9), RuntimeInspectable]
[InspectablePrefab, JsonProperty("visibility"), Key(11), RuntimeInspectable]
public PerformanceStat Visibility = new PerformanceStat();
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("ammo"), Key(10), RuntimeInspectable]
[InspectableDatabaseLink(typeof(SimpleCommodityData)), JsonProperty("ammo"), Key(12), RuntimeInspectable]
public Guid AmmoType;
[InspectablePrefab, JsonProperty("magSize"), Key(11)]
[InspectablePrefab, JsonProperty("magSize"), Key(13)]
public int MagazineSize;
[InspectablePrefab, JsonProperty("reloadTime"), Key(12)]
[InspectablePrefab, JsonProperty("reloadTime"), Key(14)]
public float ReloadTime = 1;
[InspectablePrefab, JsonProperty("spread"), Key(13)]
[InspectablePrefab, JsonProperty("spread"), Key(15)]
public PerformanceStat Spread = new PerformanceStat();
[InspectableField, JsonProperty("velocity"), Key(14)]
[InspectableField, JsonProperty("velocity"), Key(16)]
public PerformanceStat Velocity = new PerformanceStat();
}
@ -73,6 +80,7 @@ public abstract class Weapon : IActivatedBehavior
public float Damage { get; protected set; }
public float Penetration { get; protected set; }
public float DamageSpread { get; protected set; }
public float MinRange { get; protected set; }
public float Range { get; protected set; }
public float Energy { get; protected set; }
public float Heat { get; protected set; }
@ -103,6 +111,7 @@ public abstract class Weapon : IActivatedBehavior
Damage = Context.Evaluate(_data.Damage, Item.EquippableItem, Entity);
Penetration = Context.Evaluate(_data.Penetration, Item.EquippableItem, Entity);
DamageSpread = Context.Evaluate(_data.DamageSpread, Item.EquippableItem, Entity);
MinRange = Context.Evaluate(_data.MinRange, Item.EquippableItem, Entity);
Range = Context.Evaluate(_data.Range, Item.EquippableItem, Entity);
Energy = Context.Evaluate(_data.Energy, Item.EquippableItem, Entity);
Heat = Context.Evaluate(_data.Heat, Item.EquippableItem, Entity);

View file

@ -48,18 +48,9 @@ public class MegaCorporation : DatabaseEntry, INamedEntry
[InspectableDatabaseLink(typeof(PersonalityAttribute)), JsonProperty("personality"), Key(4)]
public Dictionary<Guid, float> Personality = new Dictionary<Guid, float>();
[InspectableDatabaseLink(typeof(LoadoutData)), JsonProperty("initialFleet"), Key(5)]
public Dictionary<Guid, int> InitialFleet = new Dictionary<Guid, int>();
[InspectableDatabaseLink(typeof(BlueprintData)), JsonProperty("initialTechs"), Key(6)]
public List<Guid> InitialTechnologies = new List<Guid>();
[JsonProperty("parent"), Key(7)]
public Guid HomeZone;
[InspectableField, JsonProperty("placement"), Key(8)]
public MegaPlacementType PlacementType;
[InspectableField, JsonProperty("hostile"), Key(5)]
public bool PlayerHostile;
[IgnoreMember] public string EntryName
{

View file

@ -21,6 +21,7 @@ using int2 = Unity.Mathematics.int2;
public abstract class Entity
{
public Zone Zone;
public MegaCorporation Faction;
public EquippableItem Hull;
public float3 Position;
@ -50,6 +51,7 @@ public abstract class Entity
public readonly Dictionary<string, float> Messages = new Dictionary<string, float>();
public readonly Dictionary<object, float> VisibilitySources = new Dictionary<object, float>();
public readonly Dictionary<Entity, float> EntityInfoGathered = new Dictionary<Entity, float>();
public readonly Dictionary<HardpointData, (float3 position, float3 direction)> HardpointTransforms =
new Dictionary<HardpointData, (float3 position, float3 direction)>();
@ -63,8 +65,19 @@ public abstract class Entity
public float[,] MaxArmor;
private EquippedItem[] _orderedEquipment;
private List<Weapon> _weapons = new List<Weapon>();
private List<Weapon> _weaponsInRange = new List<Weapon>();
protected bool _active;
public IEnumerable<Weapon> Weapons
{
get => _weapons;
}
public IEnumerable<Weapon> WeaponsInRange
{
get => _weaponsInRange;
}
public float MaxTemp { get; private set; }
public float MinTemp { get; private set; }
public ItemManager ItemManager { get; }
@ -246,6 +259,9 @@ public abstract class Entity
GearOccupancy[i.x, i.y] = null;
}
Mass -= itemData.Mass;
foreach (var b in item.Behaviors)
if (b is Weapon weapon)
_weapons.Add(weapon);
return item.EquippableItem;
}
@ -397,6 +413,9 @@ public abstract class Entity
{
equippedItem = new EquippedItem(ItemManager, item, hullCoord, this);
Equipment.Add(equippedItem);
foreach (var b in equippedItem.Behaviors)
if (b is Weapon weapon)
_weapons.Add(weapon);
}
foreach (var i in itemData.Shape.Coordinates)
@ -537,6 +556,15 @@ public abstract class Entity
public virtual void Update(float delta)
{
var hullData = ItemManager.GetData(Hull) as HullData;
_weaponsInRange.Clear();
if (Target.Value != null)
{
var dist = length(Position - Target.Value.Position);
foreach (var w in _weapons)
if (w.MinRange < dist && dist < w.Range)
_weaponsInRange.Add(w);
}
foreach (var v in VisibilitySources.Keys.ToArray())
{

View file

@ -111,5 +111,9 @@ public class GameplaySettings
public float TorqueFloor;
public float TorqueMultiplier;
public float VisibilityDecay;
public float TargetInfoDecay;
public float TargetDetectionInfoThreshold;
public float TargetArmorInfoThreshold;
public float TargetGearInfoThreshold;
public float ConvergenceMinimumDistance;
}

View file

@ -9,6 +9,7 @@ using System.Linq;
using System.Reflection;
using MessagePack;
using Newtonsoft.Json;
using UniRx;
using Unity.Mathematics;
using static Unity.Mathematics.math;
using quaternion = Unity.Mathematics.quaternion;
@ -26,28 +27,127 @@ public class Ship : Entity
public float2 MovementDirection;
private Thruster[] _allThrusters;
private Thruster[] _forwardThrusters;
private Thruster[] _reverseThrusters;
private Thruster[] _rightThrusters;
private Thruster[] _leftThrusters;
private Thruster[] _clockwiseThrusters;
private Thruster[] _counterClockwiseThrusters;
private HashSet<Thruster> _forwardThrusters;
private HashSet<Thruster> _reverseThrusters;
private HashSet<Thruster> _rightThrusters;
private HashSet<Thruster> _leftThrusters;
private HashSet<Thruster> _clockwiseThrusters;
private HashSet<Thruster> _counterClockwiseThrusters;
public float ForwardThrust { get; private set; }
public float ReverseThrust { get; private set; }
public float LeftStrafeThrust { get; private set; }
public float RightStrafeThrust { get; private set; }
public float ClockwiseTorque { get; private set; }
public float CounterClockwiseTorque { get; private set; }
public quaternion Rotation { get; private set; }
protected override void OnActivate()
{
_allThrusters = GetBehaviors<Thruster>().ToArray();
_forwardThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Reversed).ToArray();
_reverseThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.None).ToArray();
_rightThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise).ToArray();
_leftThrusters = _allThrusters.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Clockwise).ToArray();
_counterClockwiseThrusters = _allThrusters.Where(x => x.Torque < -ItemManager.GameplaySettings.TorqueFloor).ToArray();
_clockwiseThrusters = _allThrusters.Where(x => x.Torque > ItemManager.GameplaySettings.TorqueFloor).ToArray();
_forwardThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Reversed));
RecalculateForwardThrust();
_reverseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.None));
RecalculateReverseThrust();
_rightThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.CounterClockwise));
RecalculateRightStrafeThrust();
_leftThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Item.EquippableItem.Rotation == ItemRotation.Clockwise));
RecalculateLeftStrafeThrust();
_counterClockwiseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Torque < -ItemManager.GameplaySettings.TorqueFloor));
RecalculateCounterClockwiseTorque();
_clockwiseThrusters = new HashSet<Thruster>(_allThrusters
.Where(x => x.Torque > ItemManager.GameplaySettings.TorqueFloor));
RecalculateClockwiseTorque();
}
public Ship(ItemManager itemManager, Zone zone, EquippableItem hull) : base(itemManager, zone, hull)
{
ItemDamage.Subscribe(x =>
{
if (Hardpoints[x.item.Position.x, x.item.Position.y]?.Type == HardpointType.Thruster)
{
foreach (var behavior in x.item.Behaviors)
{
if (behavior is Thruster thruster)
{
if(_forwardThrusters.Contains(thruster)) RecalculateForwardThrust();
if(_reverseThrusters.Contains(thruster)) RecalculateReverseThrust();
if(_rightThrusters.Contains(thruster)) RecalculateRightStrafeThrust();
if(_leftThrusters.Contains(thruster)) RecalculateLeftStrafeThrust();
if(_clockwiseThrusters.Contains(thruster)) RecalculateClockwiseTorque();
if(_counterClockwiseThrusters.Contains(thruster)) RecalculateCounterClockwiseTorque();
}
}
if(x.item.EquippableItem.Rotation == ItemRotation.Reversed)
RecalculateForwardThrust();
}
});
}
private void RecalculateForwardThrust()
{
ForwardThrust = 0;
foreach (var thruster in _forwardThrusters)
{
ForwardThrust += thruster.Thrust;
}
}
private void RecalculateReverseThrust()
{
ReverseThrust = 0;
foreach (var thruster in _reverseThrusters)
{
ReverseThrust += thruster.Thrust;
}
}
private void RecalculateLeftStrafeThrust()
{
LeftStrafeThrust = 0;
foreach (var thruster in _leftThrusters)
{
LeftStrafeThrust += thruster.Thrust;
}
}
private void RecalculateRightStrafeThrust()
{
RightStrafeThrust = 0;
foreach (var thruster in _rightThrusters)
{
RightStrafeThrust += thruster.Thrust;
}
}
private void RecalculateClockwiseTorque()
{
ClockwiseTorque = 0;
foreach (var thruster in _clockwiseThrusters)
{
ClockwiseTorque += thruster.Torque;
}
}
private void RecalculateCounterClockwiseTorque()
{
CounterClockwiseTorque = 0;
foreach (var thruster in _counterClockwiseThrusters)
{
CounterClockwiseTorque -= thruster.Torque;
}
}
public override void Update(float delta)

View file

@ -16,6 +16,7 @@ using Random = Unity.Mathematics.Random;
public class Zone
{
public Action<string> Log;
//public HashSet<Guid> Planets = new HashSet<Guid>();
public ReactiveCollection<Entity> Entities = new ReactiveCollection<Entity>();
//public Dictionary<Guid, OrbitData> Orbits = new Dictionary<Guid, OrbitData>();
@ -24,10 +25,10 @@ public class Zone
public Dictionary<Guid, Orbit> Orbits = new Dictionary<Guid, Orbit>();
public Dictionary<Guid, AsteroidBelt> AsteroidBelts = new Dictionary<Guid, AsteroidBelt>();
public PlanetSettings Settings;
private HashSet<Guid> _updatedOrbits = new HashSet<Guid>();
public PlanetSettings Settings;
private float _time;
private Random _random;
@ -121,6 +122,11 @@ public class Zone
// Root orbit is fixed at origin
if(orbitID==Guid.Empty)
return float2.zero;
if (!Orbits.ContainsKey(orbitID))
{
Log?.Invoke("Requested orbit is not part of this zone!");
return float2.zero;
}
if (!_updatedOrbits.Contains(orbitID))
{