This commit is contained in:
CortexCore 2023-11-06 01:17:23 +08:00
parent bd40165ade
commit 5446067f91
114 changed files with 2023 additions and 414 deletions

View File

@ -26,6 +26,7 @@ namespace BITKit
}
public static class Time
{
public static float ElapsedTime { get; internal set; }
public static float DeltaTime { get; internal set; }
public static double TimeAsDouble { get; internal set; }
@ -286,7 +287,9 @@ namespace BITKit
BIT4Log.Warning<BITApp>($"{nameof(BITApp)}初始化错误:");
BIT4Log.LogException(e);
}
#if NET5_0_OR_GREATER
ServiceProvider = ServiceCollection.BuildServiceProvider();
#endif
}
public static void Stop()
{

View File

@ -4,7 +4,7 @@ using System.ComponentModel.Design;
#if NET5_0_OR_GREATER
using Microsoft.Extensions.DependencyInjection;
#endif
namespace BITKit.Core.Entites
namespace BITKit.Entities
{
/// <summary>
/// 基本实体
@ -17,19 +17,31 @@ namespace BITKit.Core.Entites
IEntityComponent[] Components { get; }
bool RegisterComponent<T>(T component);
IServiceProvider ServiceProvider { get; }
#if NET5_0_OR_GREATER
IServiceCollection ServiceCollection { get; }
#endif
void Inject(object obj);
}
/// <summary>
/// 基本实体组件
/// </summary>
public interface IEntityComponent:IAwake,IStart
public interface IEntityComponent
{
Type BaseType { get; }
IEntity Entity { get; set; }
#if NET5_0_OR_GREATER
void BuildService(IServiceCollection serviceCollection);
#endif
}
public interface IEntityBehavior:IEntityComponent
{
void Initialize(IEntity _entity);
void OnAwake();
void OnStart();
void OnUpdate(float deltaTime);
void OnFixedUpdate(float deltaTime);
void OnLateUpdate(float deltaTime);
void OnDestroyComponent();
}
/// <summary>
/// 基本实体服务
/// </summary>

View File

@ -65,9 +65,9 @@ namespace BITKit
public bool TryGetEntried(out T value)
{
EnsureConfiguration();
if (index is not -1)
if (m_index is not -1)
{
value = list[index];
value = list[m_index];
return true;
}
value = default;
@ -86,31 +86,30 @@ namespace BITKit
else
{
var currentIndex = m_index;
m_index = index;
if (currentIndex is not -1 && list.TryGetElementAt(currentIndex, out var element))
if (currentIndex is not -1 && list.TryGetElementAt(currentIndex, out var currentElement))
{
element.Exit();
currentElement.Exit();
try
{
await element.ExitAsync();
await currentElement.ExitAsync();
}
catch (OperationCanceledException)
{
}
element.IsEntered = false;
OnExit?.Invoke(element);
currentElement.IsEntered = false;
OnExit?.Invoke(currentElement);
}
if (index is not -1 && list.TryGetElementAt(index, out element))
m_index = index;
if (index is not -1 && list.TryGetElementAt(index, out var nextElement))
{
element.IsEntered = true;
element.Entry();
nextElement.IsEntered = true;
nextElement.Entry();
try
{
await element.EntryAsync();
await nextElement.EntryAsync();
}
catch (OperationCanceledException){}
OnEntry?.Invoke(element);
OnEntry?.Invoke(nextElement);
}
}
completed = true;

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 07743e56508d72f4bbfa9a075927d42c
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,7 @@
using System.Collections;
using System.Collections.Generic;
namespace BITKit.UniversalInputSystem
{
}

View File

@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 5ca4ab5daca5d054caf8c917c9ca6aa7
guid: 752666e8ffc64d74ea6a34b805789c51
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@ -3,6 +3,25 @@ using System.Collections.Generic;
namespace BITKit.StateMachine
{
public struct EmptyState:IState
{
public bool Enabled { get; set; }
public void Initialize()
{
}
public void OnStateEntry(IState old)
{
}
public void OnStateUpdate(float deltaTime)
{
}
public void OnStateExit(IState old, IState newState)
{
}
}
public interface IState
{
bool Enabled { get; set; }

View File

@ -9,6 +9,7 @@
{
bool Allow { get; set; }
T Value { get; set; }
T IfNotAllow(T value);
}
[System.Serializable]
public class Optional<T> : IOptional<T>
@ -29,6 +30,11 @@
set=>this.value=value;
}
public T IfNotAllow(T other)
{
return Allow ? Value : other;
}
public void SetValueThenAllow(T newValue)
{
value = newValue;

View File

@ -6,7 +6,7 @@ AnimationClip:
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Emety_Bolt
m_Name: Emety_BoltAction
serializedVersion: 7
m_Legacy: 0
m_Compressed: 0

View File

@ -0,0 +1,53 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!74 &7400000
AnimationClip:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Empty_Fire
serializedVersion: 7
m_Legacy: 0
m_Compressed: 0
m_UseHighQualityCurve: 1
m_RotationCurves: []
m_CompressedRotationCurves: []
m_EulerCurves: []
m_PositionCurves: []
m_ScaleCurves: []
m_FloatCurves: []
m_PPtrCurves: []
m_SampleRate: 60
m_WrapMode: 0
m_Bounds:
m_Center: {x: 0, y: 0, z: 0}
m_Extent: {x: 0, y: 0, z: 0}
m_ClipBindingConstant:
genericBindings: []
pptrCurveMapping: []
m_AnimationClipSettings:
serializedVersion: 2
m_AdditiveReferencePoseClip: {fileID: 0}
m_AdditiveReferencePoseTime: 0
m_StartTime: 0
m_StopTime: 1
m_OrientationOffsetY: 0
m_Level: 0
m_CycleOffset: 0
m_HasAdditiveReferencePose: 0
m_LoopTime: 1
m_LoopBlend: 0
m_LoopBlendOrientation: 0
m_LoopBlendPositionY: 0
m_LoopBlendPositionXZ: 0
m_KeepOriginalOrientation: 0
m_KeepOriginalPositionY: 1
m_KeepOriginalPositionXZ: 0
m_HeightFromFeet: 0
m_Mirror: 0
m_EditorCurves: []
m_EulerEditorCurves: []
m_HasGenericRootTransform: 0
m_HasMotionFloatCurves: 0
m_Events: []

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4c9e9f549481a1e48bff1e9bbfa4eaa2
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 7400000
userData:
assetBundleName:
assetBundleVariant:

View File

@ -56,7 +56,7 @@
"id": "9db494c5-bec3-4b09-bd5f-66ba07a3a729",
"expectedControlType": "Button",
"processors": "",
"interactions": "Tap,Hold,Press",
"interactions": "Press,Tap,Hold",
"initialStateCheck": false
},
{

View File

@ -0,0 +1,153 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &-234880573292393242
MonoBehaviour:
m_ObjectHideFlags: 11
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
m_Name:
m_EditorClassIdentifier:
version: 7
--- !u!21 &2100000
Material:
serializedVersion: 8
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Default_Lit
m_Shader: {fileID: 4800000, guid: 0406db5a14f94604a8c57ccfbc9f3b46, type: 3}
m_Parent: {fileID: 0}
m_ModifiedSerializedProperties: 0
m_ValidKeywords: []
m_InvalidKeywords:
- _FLIPBOOKBLENDING_OFF
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap:
RenderType: Opaque
disabledShaderPasses: []
m_LockedProperties:
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BaseMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_Lightmaps:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_LightmapsInd:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- unity_ShadowMasks:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Ints: []
m_Floats:
- _AlphaClip: 0
- _AlphaToMask: 0
- _Blend: 0
- _BlendModePreserveSpecular: 1
- _BlendOp: 0
- _BumpScale: 1
- _CameraFadingEnabled: 0
- _CameraFarFadeDistance: 2
- _CameraNearFadeDistance: 1
- _ClearCoatMask: 0
- _ClearCoatSmoothness: 0
- _ColorMode: 0
- _Cull: 2
- _Cutoff: 0.5
- _DetailAlbedoMapScale: 1
- _DetailNormalMapScale: 1
- _DistortionBlend: 0.5
- _DistortionEnabled: 0
- _DistortionStrength: 1
- _DistortionStrengthScaled: 0.1
- _DstBlend: 0
- _DstBlendAlpha: 0
- _EnvironmentReflections: 1
- _FlipbookBlending: 0
- _FlipbookMode: 0
- _GlossMapScale: 0
- _Glossiness: 0
- _GlossyReflections: 0
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.005
- _QueueOffset: 0
- _ReceiveShadows: 1
- _Smoothness: 0.5
- _SmoothnessSource: 0
- _SmoothnessTextureChannel: 0
- _SoftParticlesEnabled: 0
- _SoftParticlesFarFadeDistance: 1
- _SoftParticlesNearFadeDistance: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _SrcBlendAlpha: 1
- _Surface: 0
- _WorkflowMode: 1
- _ZWrite: 1
m_Colors:
- _BaseColor: {r: 1, g: 1, b: 1, a: 1}
- _BaseColorAddSubDiff: {r: 0, g: 0, b: 0, a: 0}
- _CameraFadeParams: {r: 0, g: 0, b: 0, a: 0}
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SoftParticleFadeParams: {r: 0, g: 0, b: 0, a: 0}
- _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
m_BuildTextureStacks: []

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8c12d604efc78e94b949674757f0f9eb
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@ -5,5 +5,6 @@ using UnityEngine;
public class AnimationProperty : MonoBehaviour
{
public static implicit operator float(AnimationProperty self) => self.value;
public float value;
[SerializeField]private float value;
public float Value => value;
}

View File

@ -130,6 +130,7 @@ namespace BITKit
private void Update()
{
BITApp.Time.ElapsedTime = Time.time;
BITApp.Time.DeltaTime = Time.deltaTime;
BITApp.Time.TimeAsDouble = Time.timeAsDouble;
}

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using UnityEngine;
namespace BITKit
{
public class PhysicsDoor : MonoBehaviour, IAction
public class PhysicsDoor : MonoBehaviour, IAction,IDescription
{
public enum State
{
@ -12,7 +12,7 @@ namespace BITKit
HalfOpen,
Locked,
}
[SerializeField] private string description;
[SerializeField] private bool allowPhysics = true;
[SerializeField] private Rigidbody root;
[SerializeField] private Vector3 openEuler;
@ -69,5 +69,6 @@ namespace BITKit
};
Set(isClosed);
}
public string Name => description;
}
}

View File

@ -1,12 +1,14 @@
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using BITKit.Animations;
namespace BITKit.Entities
{
public sealed class EntityAnimator : EntityComponent
public sealed class EntityAnimator : EntityBehavior
{
[SerializeField] private Animator[] animators;
[SerializeField] private UnityAnimator[] animators;
[SerializeReference, SubclassSelector] private References[] animationKeyWords;
[SerializeReference, SubclassSelector] private References _rootVelocity;
[SerializeReference, SubclassSelector] private References[] boolParameters;
@ -18,18 +20,18 @@ namespace BITKit.Entities
}
public override void OnStart()
{
entity.AddListener<string>(Constant.Animation.Play, Play);
UnityEntity.AddListener<string>(Constant.Animation.Play, Play);
}
private void Play(string animationName)
{
if (enabled is false) return;
if (animationKeyWords.Length is 0 || keyWords.Contains(animationName))
{
animators.ForEach(x =>
{
if (!x.isActiveAndEnabled) return;
animationName = animationName.Replace(".", "_");
x.SetTrigger(animationName);
x.Play(animationName);
});
}
}
@ -40,7 +42,7 @@ namespace BITKit.Entities
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
x.SetBool(boolPar, entity.Get<bool>(boolPar));
x.animator.SetBool(boolPar, UnityEntity.Get<bool>(boolPar));
});
}
foreach (var floatPar in floatParameters)
@ -48,18 +50,22 @@ namespace BITKit.Entities
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
x.SetFloat(floatPar, entity.Get<float>(floatPar));
x.animator.SetFloat(floatPar, UnityEntity.Get<float>(floatPar));
});
}
}
private void OnAnimatorMove()
{
entity.Set(_rootVelocity, animators[0].velocity);
if (enabled is false) return;
if (_rootVelocity is not null && UnityEntity is not null)
UnityEntity.Set(_rootVelocity, animators[0].animator.velocity);
}
// ReSharper disable once UnusedMember.Local
private void AnimationEvent(string eventName)
{
entity.Invoke(Constant.Animation.OnEvent, eventName);
UnityEntity.Invoke(Constant.Animation.OnEvent, eventName);
}
}
}

View File

@ -4,12 +4,12 @@ using UnityEngine;
using BITKit.Sensors;
namespace BITKit.Entities
{
public class EntityAudioObject : EntityComponent, IAudioObject
public class EntityAudioObject : EntityBehavior, IAudioObject
{
float volume;
public override void OnStart()
{
entity.AddListener<AudioSO>(OnAuioSO);
UnityEntity.AddListener<AudioSO>(OnAuioSO);
}
public override void OnFixedUpdate(float deltaTime)
{

View File

@ -2,7 +2,7 @@ using BITKit.Entities.Player;
using UnityEngine;
namespace BITKit.Entities
{
public class EntityCamera : EntityPlayerComponent
public class EntityCamera : EntityPlayerBehavior
{
[Header(Constant.Header.Components)]
public Behaviour aliveCamera;
@ -11,7 +11,7 @@ namespace BITKit.Entities
[SerializeReference, SubclassSelector] public IReference _onSetAlive;
public override void OnAwake()
{
var heal = entity.Get<IHealth>();
var heal = UnityEntity.Get<IHealth>();
heal.OnSetAlive += OnSetAlive;
}
private void OnSetAlive(bool alive)

View File

@ -4,7 +4,7 @@ using UnityEngine;
using UnityEngine.Rendering;
namespace BITKit.Entities.Player.Character
{
public class EntityCharacter : EntityPlayerComponent
public class EntityCharacter : EntityPlayerBehavior
{
[Header(Constant.Header.Components)]
[SerializeField] private Renderer[] fpvRenderer = Array.Empty<Renderer>();
@ -13,7 +13,7 @@ namespace BITKit.Entities.Player.Character
[SerializeReference, SubclassSelector] public References _getDamage;
public override void OnStart()
{
var heal = entity.Get<IHealth>();
var heal = UnityEntity.Get<IHealth>();
heal.OnSetAlive += OnSetAlive;
heal.OnSetHealthPoint += OnSetHP;
}
@ -33,7 +33,7 @@ namespace BITKit.Entities.Player.Character
}
private void OnSetHP(int hp)
{
entity.Invoke<string>(Constant.Animation.Play, _getDamage);
UnityEntity.Invoke<string>(Constant.Animation.Play, _getDamage);
}
private void SetFPV(bool isFpv)
{

View File

@ -6,7 +6,7 @@ using UnityEngine.InputSystem;
namespace BITKit
{
public class NavAgentMovement: StateBasedComponent<IEntityMovementState>,IEntityMovement
public class NavAgentMovement: StateBasedBehavior<IEntityMovementState>,IEntityMovement
{
#region
[SerializeField] private NavMeshAgent agent;
@ -67,8 +67,8 @@ namespace BITKit
GroundVelocity = _groundVelocity;
IsGrounded = agent.isOnOffMeshLink is false;
entity.Set<bool>("IsMoving",Velocity.sqrMagnitude>=0.16f);
entity.Set<float>("SqrMagnitude",Velocity.sqrMagnitude);
UnityEntity.Set<bool>("IsMoving",Velocity.sqrMagnitude>=0.16f);
UnityEntity.Set<float>("SqrMagnitude",Velocity.sqrMagnitude);
if (!isDead) return;

View File

@ -6,7 +6,7 @@ using UnityEngine.InputSystem;
namespace BITKit.Entities.Movement
{
public class RigidbodyBasedMovement : StateBasedComponent<IEntityMovementState>,IEntityMovement
public class RigidbodyBasedMovement : StateBasedBehavior<IEntityMovementState>,IEntityMovement
{
[SerializeField] private new Rigidbody rigidbody;
[SerializeField] private Animator animator;
@ -20,6 +20,11 @@ namespace BITKit.Entities.Movement
public Vector3 GroundVelocity { get; }
public Vector3 AngularVelocity { get; }
public bool IsGrounded { get; }
[Inject(true)]
private IHealth health;
public void SyncMovement(Vector3 velocity, Vector3 position, Quaternion rotation, bool isGrounded)
{
}
@ -37,6 +42,20 @@ namespace BITKit.Entities.Movement
}
public event Action<object> OnCommand;
public override void OnAwake()
{
base.OnAwake();
if (health is not null)
{
health.OnSetAlive += OnSetAlive;
}
}
private void OnSetAlive(bool obj)
{
rigidbody.isKinematic = !obj;
}
public override void OnFixedUpdate(float deltaTime)
{
rigidbody.MovePosition(rigidbody.position + Velocity * deltaTime

View File

@ -6,7 +6,7 @@ using UnityEngine;
namespace BITKit
{
public class AutoHealComponent : EntityComponent,IDamageCallback
public class AutoHealBehavior : EntityBehavior,IDamageCallback
{
[SerializeField] private IntervalUpdate healDelayInterval;
[SerializeField] private IntervalUpdate healInterval;
@ -14,17 +14,12 @@ namespace BITKit
private readonly ValidHandle allowHeal = new();
[Inject]
private IHealth _health;
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_entity.RegisterCallback<IDamageCallback>(this);
}
public override void OnStart()
{
_health = entity.Get<IHealth>();
_health = UnityEntity.Get<IHealth>();
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
private void Update()

View File

@ -1,53 +1,50 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BITKit.Entities;
using UnityEngine;
namespace BITKit
{
public class AutoRespawnComponent : EntityComponent,IAction
public class AutoRespawnBehavior : EntityBehavior,IAction
{
[SerializeField] private IntervalUpdate respawnInterval;
private bool requestRespawn;
[Inject] private IHealth _health;
private int _initialHp;
private CancellationTokenSource _cancellationTokenSource;
public override void OnAwake()
{
_initialHp=_health.HealthPoint;
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
public override void OnUpdate(float deltaTime)
{
if (requestRespawn && respawnInterval.AllowUpdate)
{
requestRespawn = false;
Execute();
}
}
public void OnSetAlive(bool alive)
private async void OnSetAlive(bool alive)
{
if (alive)
{
requestRespawn = false;
_cancellationTokenSource?.Cancel();
}
else
{
respawnInterval.Reset();
requestRespawn = true;
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
try
{
await Task.Delay(TimeSpan.FromSeconds(respawnInterval.Interval), _cancellationTokenSource.Token);
destroyCancellationToken.ThrowIfCancellationRequested();
Execute();
}
catch(MissingReferenceException){}
catch (OperationCanceledException){}
}
}
public void OnSetHP(int hp)
{
}
public void Execute()
{
if (TryGetComponent<IHealth>(out var health))
{
health.HealthPoint = 100;
}
if (_health.IsAlive is false)
_health.HealthPoint = _initialHp;
}
}

View File

@ -61,8 +61,8 @@ namespace BITKit.Entities
}
public record DamageMessage
{
public IEntity Initiator;
public IEntity Target;
public IUnityEntity Initiator;
public IUnityEntity Target;
public bool RawDamage;
public int Damage;
public IDamagable Hit;
@ -75,7 +75,7 @@ namespace BITKit.Entities
}
public interface IDamagable
{
IEntity Entity { get; }
IUnityEntity UnityEntity { get; }
Rigidbody Rigidbody { get; }
void GiveDamage(DamageMessage message);
}
@ -99,11 +99,6 @@ namespace BITKit.Entities
damageMessage.Initiator?.Invoke(damageMessage);
damageMessage.Target?.Invoke(damageMessage);
foreach (var x in damageMessage.Target?.GetCallbacks<IDamageCallback>()!)
{
x.OnGetDamage(damageMessage);
}
OnEntityDamaged?.Invoke(damageMessage);
if (heal.IsAlive is false)
{

View File

@ -26,7 +26,7 @@ namespace BITKit.Entities
bool IsAlive { get; }
}
[CustomType(typeof(IHealth))]
public class EntityHealth : EntityComponent, IHealth
public class EntityHealth : EntityBehavior, IHealth
{
[Header(Constant.Header.Settings)]
[SerializeField] private int healthPoint = 100;
@ -49,7 +49,7 @@ namespace BITKit.Entities
public bool IsAlive { get; private set; }
public override void OnAwake()
{
entity.AddListener<DamageMessage>(OnGetDamage);
UnityEntity.AddListener<DamageMessage>(OnGetDamage);
}
public override void OnStart()
@ -83,7 +83,7 @@ namespace BITKit.Entities
private void OnGetDamage(DamageMessage damageMessage)
{
if (damageMessage.Target != entity) return;
if (damageMessage.Target != UnityEntity) return;
if (IsAlive is false) return;
var damage = damageMessage.Damage;
foreach (var x in OnDamageFactory.CastAsFunc().Reverse())

View File

@ -9,7 +9,7 @@ using UnityEngine.Events;
namespace BITKit.Entities
{
public class GetDamageComponent : EntityComponent
public class GetDamageBehavior : EntityBehavior
{
private readonly Queue<DamageMessage> DamageMessages = new();
[SerializeField] private UnityEvent<DamageMessage> onGetDamage;
@ -17,11 +17,11 @@ namespace BITKit.Entities
private IDamageCallback[] callbacks;
public override void OnAwake()
{
entity.AddListener<DamageMessage>(OnGetDamage);
UnityEntity.AddListener<DamageMessage>(OnGetDamage);
}
private void OnGetDamage(DamageMessage obj)
{
if (obj.Target != entity) return;
if (obj.Target != UnityEntity) return;
DamageMessages.Enqueue(obj);
onGetDamage?.Invoke(obj);
foreach (var x in callbacks)

View File

@ -4,13 +4,13 @@ using UnityEngine;
using BITKit;
namespace BITKit.Entities
{
public class EntityHitbox : EntityComponent,IDamagable
public class EntityHitbox : EntityBehavior,IDamagable
{
IEntity IDamagable.Entity => entity;
IUnityEntity IDamagable.UnityEntity => UnityEntity;
public Rigidbody Rigidbody => m_rigidbody;
public void GiveDamage(DamageMessage message)
{
entity.Invoke(message);
UnityEntity.Invoke(message);
}
[SerializeField]private Rigidbody m_rigidbody;

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e6a1d9b4067d2d84da86a7e043b40806
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,4 @@
{
"name": "BITKit.Entities.InputSystem",
"references":[ "GUID:14fe60d984bf9f84eac55c6ea033a8f4", "GUID:f6155d9ae143f3949ac54e8355593d6c", "GUID:7efac18f239530141802fb139776f333", "GUID:709caf8d7fb6ef24bbba0ab9962a3ad0" ]
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7fa5fe8aad740144c9ddda741d067c44
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,68 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.Entities.InputSystem
{
public class EntityInputSystem : EntityBehavior
{
protected readonly InputActionGroup inputActionGroup = new()
{
allowGlobalActivation = true
};
[Inject(true)]
private IHealth _health;
[Inject(true)]
private IEntityOverride _override;
#if UNITY_EDITOR
[SerializeField,HideInInspector] internal bool Allow;
#endif
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
UnityEntity.AddService(inputActionGroup);
}
public override void OnAwake()
{
base.OnAwake();
inputActionGroup.allowInput.AddListener(x=>Allow=x);
if (_health is not null)
{
_health.OnSetAlive += x =>
{
inputActionGroup.allowInput.SetElements(_health,x);
};
}
if (_override is not null)
{
_override.OnOverride += x =>
{
inputActionGroup.allowInput.SetDisableElements(_override,x);
};
}
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(EntityInputSystem))]
public sealed class EntityInputSystemInspector : BITInspector<EntityInputSystem>
{
public override VisualElement CreateInspectorGUI()
{
FillDefaultInspector();
var checkBox = root.Create<Toggle>();
checkBox.label = "Allow Input";
checkBox.SetEnabled(false);
checkBox.BindProperty(serializedObject.FindProperty(nameof(EntityInputSystem.Allow)));
return root;
}
}
#endif
}

View File

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

View File

@ -7,7 +7,7 @@ using UnityEngine.InputSystem.Interactions;
namespace BITKit.Entities.Player
{
[CustomType(typeof(ISelector))]
public class EntityInteractive : EntityPlayerComponent,ISelector
public class EntityInteractive : EntityPlayerBehavior,ISelector
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISensor sensor;
@ -17,8 +17,6 @@ namespace BITKit.Entities.Player
private IntervalUpdate cd = new(0.08f);
[Inject]
private IHealth _health;
[Inject]
private InputActionGroup _inputActionReference;
public override void OnStart()
{
@ -82,6 +80,10 @@ namespace BITKit.Entities.Player
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
else
{
}
selected.SetSelectionState(SelectionState.Active);
OnActive?.Invoke(selected);

View File

@ -6,7 +6,7 @@ using UnityEngine.Events;
using Cysharp.Threading.Tasks;
namespace BITKit.Entities
{
public class EntityLocomotion : EntityComponent
public class EntityLocomotion : EntityBehavior
{
[Header(Constant.Header.Settings)]

View File

@ -8,23 +8,45 @@ using UnityEngine;
namespace BITKit.Entities
{
[CustomType(typeof(IEntityPhysics))]
public class EntityPhysics : EntityComponent,IEntityPhysics
public class EntityPhysics : EntityBehavior,IEntityPhysics
{
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody[] rigidbodies;
[SerializeField] private Collider[] ragdollColliders;
[SerializeField] private Joint joint;
[SerializeField] private Joint[] joints;
[SerializeField] private new Rigidbody rigidbody;
private CancellationToken _cancellationToken;
[Inject]
private IHealth _health;
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointXMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointYMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointZMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularXMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularYMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularZMotions=new();
public override void OnAwake()
{
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_cancellationToken = entity.Get<CancellationToken>();
_cancellationToken = UnityEntity.Get<CancellationToken>();
foreach (var x in joints)
{
switch (x)
{
case ConfigurableJoint configurableJoint:
_jointXMotions.Add(configurableJoint,configurableJoint.xMotion);
_jointYMotions.Add(configurableJoint,configurableJoint.yMotion);
_jointZMotions.Add(configurableJoint,configurableJoint.zMotion);
_jointAngularXMotions.Add(configurableJoint,configurableJoint.angularXMotion);
_jointAngularYMotions.Add(configurableJoint,configurableJoint.angularYMotion);
_jointAngularZMotions.Add(configurableJoint,configurableJoint.angularZMotion);
break;
}
}
}
private async void OnSetAlive(bool alive)
private async void OnSetAlive(bool alive)
{
IsPhysics = !alive;
if (animator)
@ -38,15 +60,29 @@ namespace BITKit.Entities
}
catch (OperationCanceledException)
{
}
if (alive is false && joint is not null)
foreach (var joint in joints)
{
Destroy(joint);
switch (joint)
{
case ConfigurableJoint configurableJoint:
configurableJoint.xMotion = alive ? _jointXMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.yMotion = alive ? _jointYMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.zMotion = alive ? _jointZMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularXMotion =
alive ? _jointAngularXMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularYMotion =
alive ? _jointAngularYMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularZMotion =
alive ? _jointAngularZMotions[joint] : ConfigurableJointMotion.Free;
break;
}
}
}
public void OnSetHP(int hp)
{
}

View File

@ -6,7 +6,7 @@ using UnityEngine;
namespace BITKit.Entities.Slot
{
[CustomType(typeof(IEntitySlot<Transform>))]
public sealed class UnityEntitySlot : EntityComponent, IEntitySlot<Transform>
public sealed class UnityEntitySlot : EntityBehavior, IEntitySlot<Transform>
{
[SerializeField] private SerializedDictionary<string,Transform> dictionary = new();
public IDictionary<string, Transform> Slots => dictionary;

View File

@ -5,7 +5,7 @@ using UnityEngine;
namespace BITKit.Entities
{
public class SlotComponent : EntityComponent
public class SlotBehavior : EntityBehavior
{
public SerializedDictionary<string,Transform> slots;
}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 717c72a7a267b5341a874e6d50d7df49
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,20 @@
{
"name": "BITKit.Entities.VFX",
"rootNamespace": "",
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:709caf8d7fb6ef24bbba0ab9962a3ad0",
"GUID:ea5474181b324dd49a5976cd68f44f18",
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1eb13dc7c3cb5a444877a995967ed591
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,27 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace BITKit.Entities.VFX
{
public class EntityVFXPlayer : EntityBehavior
{
[SerializeReference,SubclassSelector] private IReference[] vfxReferences;
[SerializeField] private VFXPlayer vfxPlayer;
private readonly List<string> keyWords=new();
public override void OnAwake()
{
base.OnAwake();
keyWords.AddRange(vfxReferences.Select(x=>x.Value));
UnityEntity.AddListener<string>(Constant.Animation.Play, Play);
}
private void Play(string animationName)
{
if (isActiveAndEnabled is false) return;
if (keyWords.Contains(animationName) is false) return;
vfxPlayer.Execute();
}
}
}

View File

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

View File

@ -5,29 +5,27 @@ using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using BITKit.Core.Entites;
using BITKit.Entities;
using Cysharp.Threading.Tasks;
using UnityEngine.UIElements;
// ReSharper disable RedundantTypeArgumentsOfMethod
namespace BITKit.Entities
{
public class Entity : MonoBehaviour, IEntity
public class Entity : MonoBehaviour, IUnityEntity
{
private readonly GenericEvent genericEvent = new();
private readonly Processor processor = new();
public IEntityComponent[] entityComponents { get; set; }
public ulong Id { get; private set; }
public CancellationToken CancellationToken => _cancellationToken;
public CancellationToken CancellationToken { get; private set; }
public IEntityBehavior[] Behaviors { get;private set; }
public IEntityComponent[] Components => Behaviors.Cast<IEntityComponent>().ToArray();
Core.Entites.IEntityComponent[] Core.Entites.IEntity.Components => _components;
bool Core.Entites.IEntity.RegisterComponent<T>(T component)
bool Entities.IEntity.RegisterComponent<T>(T component)
{
throw new InvalidOperationException("Unity Entity can't register component");
}
IServiceProvider Core.Entites.IEntity.ServiceProvider=> throw new InvalidOperationException("Unity Entity can't register component");
IServiceProvider Entities.IEntity.ServiceProvider=> throw new InvalidOperationException("Unity Entity can't register component");
public void Inject(object obj)
{
foreach (var fieldInfo in obj
@ -44,7 +42,7 @@ namespace BITKit.Entities
{
case null:
break;
case Core.Entites.IEntityComponent entityComponent:
case Entities.IEntityComponent entityComponent:
if(entityComponent.Entity.Id == Id)
continue;
break;
@ -61,23 +59,37 @@ namespace BITKit.Entities
}
else if(attribute?.CanBeNull is false)
{
BIT4Log.Warning<Entity>($"{name}未找到{type.FullName}");
BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
BIT4Log.Warning<Entity>($"{name}未找到{obj.GetType().Name}需要的{type.FullName}");
//BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
}
}
}
private CancellationToken _cancellationToken;
public void AddService<T>(T service)
{
AddService(typeof(T),service);
}
public void AddService(object service)
{
AddService(service.GetType(),service);
}
public void AddService(Type type, object service)
{
genericEvent.Set(type,service);
genericEvent.Set(type.FullName, service);
genericEvent.SetDirect(type.FullName,service);
}
private bool isInitialized;
private Core.Entites.IEntityComponent[] _components => entityComponents.Cast<Core.Entites.IEntityComponent>().ToArray();
private void Awake()
{
Id = (ulong)Guid.NewGuid().GetHashCode();
_cancellationToken = gameObject.GetCancellationTokenOnDestroy();
Set(_cancellationToken);
entityComponents = GetComponentsInChildren<IEntityComponent>(true).Distinct().ToArray();
CancellationToken = gameObject.GetCancellationTokenOnDestroy();
Set(CancellationToken);
Behaviors = GetComponentsInChildren<IEntityBehavior>(true).Distinct().ToArray();
UnityEntitiesService.Register(this);
}
private void Start()
@ -85,6 +97,7 @@ namespace BITKit.Entities
try
{
var monoBehaviours = GetComponentsInChildren<MonoBehaviour>(true);
Behaviors.ForEach(x => x.Initialize(this));
foreach (var x in monoBehaviours)
{
foreach (var att in x
@ -95,9 +108,7 @@ namespace BITKit.Entities
.OfType<CustomTypeAttribute>()
)
{
genericEvent.Set(att.Type,x);
genericEvent.Set(att.Type.FullName, x);
genericEvent.SetDirect(att.Type.FullName,x);
AddService(att.Type, x);
}
genericEvent.Set(x.GetType(),x);
}
@ -105,10 +116,10 @@ namespace BITKit.Entities
{
Inject(x);
}
entityComponents.ForEach(x => x.Initialize(this));
entityComponents.ForEach(x => x.OnAwake());
entityComponents.ForEach(x => x.OnStart());
Behaviors.ForEach(x => x.OnAwake());
Behaviors.ForEach(x => x.OnStart());
isInitialized = true;
}
catch (Exception e)
@ -122,21 +133,21 @@ namespace BITKit.Entities
{
if (isInitialized)
{
entityComponents.ForEach(x => x.OnDestroyComponent());
Behaviors.ForEach(x => x.OnDestroyComponent());
}
UnityEntitiesService.UnRegister(this);
}
private void Update()
{
entityComponents.ForEach(x => x.OnUpdate(Time.deltaTime));
Behaviors.ForEach(x => x.OnUpdate(Time.deltaTime));
}
private void FixedUpdate()
{
entityComponents.ForEach(x => x.OnFixedUpdate(Time.fixedDeltaTime));
Behaviors.ForEach(x => x.OnFixedUpdate(Time.fixedDeltaTime));
}
private void LateUpdate()
{
entityComponents.ForEach(x => x.OnLateUpdate(Time.deltaTime));
Behaviors.ForEach(x => x.OnLateUpdate(Time.deltaTime));
}
public void AddListener<T>(Action<T> action) => genericEvent.AddListener<T>(action);
public void Invoke<T>(T value) => genericEvent.Invoke<T>(value);
@ -155,42 +166,6 @@ namespace BITKit.Entities
}
public void Set<T>(T value) => genericEvent.Set<T>(value);
public void Set<T>(string key = Constant.System.Internal, T value = default) => genericEvent.Set<T>(key, value);
public T GetContext<T>(T value = default) => processor.GetContext<T>(value);
public void AddProcessor<T>(Func<T, T> func) => processor.AddProcessor<T>(func);
public void RemoveProcessor<T>(Func<T, T> func) => processor.RemoveProcessor<T>(func);
public T GetContext<T>(string key, T value) => processor.GetContext<T>(value);
public void AddProcessor<T>(string key, Func<T, T> func) => processor.AddProcessor<T>(key, func);
public void RemoveProcessor<T>(string key, Func<T, T> func) => processor.RemoveProcessor<T>(key, func);
public void RegisterCallback<T>(T t)
{
var value = GetCallbacks<T>() as List<T>;
value!.Add(t);
}
public void UnRegisterCallback<T>(T t)
{
var value = GetCallbacks<T>() as List<T>;
value!.Remove(t);
}
public IEnumerable<T> GetCallbacks<T>()
{
var value = Get<List<T>>(nameof(ICallback)).CreateOrAddIfEmety(() =>
{
List<T> newList = new();
Set<List<T>>(nameof(ICallback), newList);
return newList;
});
if (value is null)
{
Debug.LogWarning("List is Null");
}
return value;
}
}
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(Entity))]

View File

@ -0,0 +1,38 @@
using System;
using BITKit.Entities;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace BITKit.Entities
{
public abstract class EntityBehavior : MonoBehaviour, IEntityBehavior
{
public IEntity Entity { get; set; }
public IUnityEntity UnityEntity { get; private set; }
protected Transform Transform { get; private set; }
private IUnityEntity _mUnityEntity;
public virtual void Initialize(IEntity _entity)
{
Transform = transform;
UnityEntity = _entity as IUnityEntity;
Entity = _entity;
}
public virtual void OnAwake() { }
public virtual void OnStart() { }
public virtual void OnUpdate(float deltaTime) { }
public virtual void OnFixedUpdate(float deltaTime) { }
public virtual void OnLateUpdate(float deltaTime) { }
public virtual void OnDestroyComponent() { }
}
#if UNITY_EDITOR
[CanEditMultipleObjects]
[CustomEditor(typeof(EntityBehavior), true)]
public class EntityComponentInspector : BITInspector<EntityBehavior>
{
}
#endif
}

View File

@ -1,47 +0,0 @@
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace BITKit.Entities
{
public interface IEntityComponent:BITKit.Core.Entites.IEntityComponent
{
IEntity entity { get; }
void Initialize(IEntity _entity);
void OnUpdate(float deltaTime);
void OnFixedUpdate(float deltaTime);
void OnLateUpdate(float deltaTime);
void OnDestroyComponent();
}
public abstract class EntityComponent : MonoBehaviour, IEntityComponent
{
public IEntity entity { get; private set; }
protected Transform Transform { get; private set; }
private IEntity mEntity;
public virtual void Initialize(IEntity _entity)
{
Transform = transform;
entity = _entity;
Entity = _entity;
}
public virtual void OnAwake() { }
public virtual void OnStart() { }
public virtual void OnUpdate(float deltaTime) { }
public virtual void OnFixedUpdate(float deltaTime) { }
public virtual void OnLateUpdate(float deltaTime) { }
public virtual void OnDestroyComponent() { }
public virtual Type BaseType => GetType();
public Core.Entites.IEntity Entity { get; set; }
}
#if UNITY_EDITOR
[CanEditMultipleObjects]
[CustomEditor(typeof(EntityComponent), true)]
public class EntityComponentInspector : BITInspector<EntityComponent>
{
}
#endif
}

View File

@ -1,19 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit.Entities
{
public class EntityIdComponent : EntityComponent
{
public ulong Id;
public string Name;
public override void Initialize(IEntity _entity)
{
if (Id is 0) Id = (ulong)Guid.NewGuid().GetHashCode();
base.Initialize(_entity);
_entity.Set(this);
}
}
}

View File

@ -11,12 +11,8 @@ namespace BITKit.Entities
void RemoveOverride(object key);
event Action<bool> OnOverride;
}
public interface IEntityOverrideCallback
{
void OnEntryOverride(bool @override);
}
[CustomType(typeof(IEntityOverride))]
public class EntityOverride : EntityComponent,IEntityOverride
public class EntityOverride : EntityBehavior,IEntityOverride
{
[SerializeField,ReadOnly] private bool isOvering;
public bool IsOvering => _allowOverrideHandle;
@ -25,10 +21,10 @@ namespace BITKit.Entities
public void RemoveOverride(object key)=>_allowOverrideHandle.RemoveElement(key);
public event Action<bool> OnOverride;
public override void Initialize(IEntity _entity)
public override void Initialize(IEntity entity)
{
base.Initialize(_entity);
_entity.Set<IEntityOverride>(this);
base.Initialize(entity);
UnityEntity.Set<IEntityOverride>(this);
}
public override void OnAwake()
{

View File

@ -2,36 +2,38 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using BITKit.Core.Entites;
using BITKit.Entities;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace BITKit.Entities
{
/// <summary>Entity接口用于复杂实体</summary>
public interface IEntity :BITKit.Core.Entites.IEntity,IGenericEvent<string>, IDatabase, IProcessor, ICallback
public interface IUnityEntity :Entities.IEntity,IGenericEvent<string>, IDatabase
{
IEntityComponent[] entityComponents { get; set; }
void AddService<T>(T service);
void AddService(object service);
void AddService(Type type, object service);
}
public class IEntityReader : NetMessageReader<IEntity>
public class IEntityReader : NetMessageReader<IUnityEntity>
{
public override IEntity ReadBinary(BinaryReader reader)
public override IUnityEntity ReadBinary(BinaryReader reader)
{
var id = reader.ReadInt32();
var path = reader.ReadString();
var entity = DI.Get<IEntitiesService>().Entities[id];
return (IEntity)entity;
return (IUnityEntity)entity;
}
public override void WriteBinary(BinaryWriter writer, IEntity value)
public override void WriteBinary(BinaryWriter writer, IUnityEntity value)
{
writer.Write(value.Id);
writer.Write(value.Id);
}
private IEntity Create(int id, string path)
private IUnityEntity Create(int id, string path)
{
var entity = Addressables
.LoadAssetAsync<GameObject>(path)
.WaitForCompletion()
.GetComponent<IEntity>();
.GetComponent<IUnityEntity>();
return entity;
}
}

View File

@ -7,7 +7,7 @@ using UnityEngine;
namespace BITKit.Entities
{
public class StateBasedComponent<T> : EntityComponent,IStateMachine<T> where T : IState
public class StateBasedBehavior<T> : EntityBehavior,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public bool Enabled
@ -28,9 +28,9 @@ namespace BITKit.Entities
remove => stateMachine.OnStateChanged -= value;
}
public IDictionary<Type, T> StateDictionary => stateMachine.StateDictionary;
public override void Initialize(IEntity _entity)
public override void Initialize(IEntity entity)
{
base.Initialize(_entity);
base.Initialize(entity);
if (stateMachine is null)
{
Debug.LogWarning(GetType().Name);

View File

@ -4,13 +4,12 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using BITKit;
using BITKit.Core.Entites;
using BITKit.Entities;
using UnityEngine;
using Cysharp.Threading.Tasks;
using UnityEngine.Pool;
using IEntity = BITKit.Core.Entites.IEntity;
using IEntityComponent = BITKit.Core.Entites.IEntityComponent;
using IEntity = BITKit.Entities.IEntity;
using IEntityComponent = BITKit.Entities.IEntityComponent;
[Serializable]
public class UnityEntitiesServiceSingleton:IEntitiesService
{

View File

@ -22,12 +22,12 @@ namespace BITKit.Entities.Player
/// <summary>
/// 注册玩家
/// </summary>
/// <param name="entity">玩家实体</param>
void Register(Entity entity);
/// <param name="unityEntity">玩家实体</param>
void Register(Entity unityEntity);
/// <summary>
/// 注销玩家
/// </summary>
/// <param name="entity">玩家实体</param>
void UnRegister(Entity entity);
/// <param name="unityEntity">玩家实体</param>
void UnRegister(Entity unityEntity);
}
}

View File

@ -10,7 +10,7 @@ namespace BITKit.Entities.Player
/// <summary>
/// 玩家组件的基本实现
/// </summary>
public abstract class EntityPlayerComponent : EntityComponent, IEntityPlayerComponent
public abstract class EntityPlayerBehavior : EntityBehavior, IEntityPlayerComponent
{
public virtual void OnPlayerInitialize()
{

View File

@ -6,9 +6,8 @@ using UnityEngine;
namespace BITKit.Entities.Player
{
public class LocalPlayerComponent : EntityComponent
public class LocalPlayerBehavior : EntityBehavior
{
public override Type BaseType => typeof(LocalPlayerComponent);
private IEntityPlayerComponent[] playerComponents;
private CancellationTokenSource initializeCancellationTokenSource;
private CancellationTokenSource disposeCancellationTokenSource;
@ -31,7 +30,7 @@ namespace BITKit.Entities.Player
{
x.OnPlayerInitialized();
}
UnityPlayerServiceService.Register((Entity)entity);
UnityPlayerServiceService.Register((Entity)UnityEntity);
}
public override async void OnDestroyComponent()
{
@ -50,7 +49,7 @@ namespace BITKit.Entities.Player
x.OnPlayerDisposed();
}
disposeCancellationTokenSource.Dispose();
UnityPlayerServiceService.UnRegister((Entity)entity);
UnityPlayerServiceService.UnRegister((Entity)UnityEntity);
}
}
}

View File

@ -9,7 +9,7 @@ namespace BITKit.Entities.Player
/// 基于状态机的玩家组件
/// </summary>
/// <typeparam name="T">状态,继承于<see cref="IState"/></typeparam>
public abstract class StateBasedPlayerComponent<T> : EntityPlayerComponent,IStateMachine<T> where T : IState
public abstract class StateBasedPlayerBehavior<T> : EntityPlayerBehavior,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public override void OnAwake()

View File

@ -14,14 +14,14 @@ namespace BITKit.Entities.Player
public static event Action<Entity> OnPlayerInitialized;
public static event Action<Entity> OnPlayerDisposed;
public static Entity LocalPlayer { get;private set; }
public static void Register(Entity entity)
public static void Register(Entity unityEntity)
{
OnPlayerInitialized?.Invoke(entity);
LocalPlayer = entity;
OnPlayerInitialized?.Invoke(unityEntity);
LocalPlayer = unityEntity;
}
public static void UnRegister(Entity entity)
public static void UnRegister(Entity unityEntity)
{
OnPlayerDisposed?.Invoke(entity);
OnPlayerDisposed?.Invoke(unityEntity);
LocalPlayer = null;
}
Entity IPlayerService.LocalPlayer=>LocalPlayer;
@ -35,8 +35,8 @@ namespace BITKit.Entities.Player
add => OnPlayerDisposed += value;
remove => OnPlayerDisposed -= value;
}
void IPlayerService.Register(Entity entity)=>Register(entity);
void IPlayerService.UnRegister(Entity entity)=>UnRegister(entity);
void IPlayerService.Register(Entity unityEntity)=>Register(unityEntity);
void IPlayerService.UnRegister(Entity unityEntity)=>UnRegister(unityEntity);
}
}

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6f86267df70993b40afe97cef33ef2f4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,56 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Assertions;
namespace BITKit
{
public static class ConstraintExtensions
{
public static ParentConstraint SetParentConstraint(this Transform target, Transform parentSource,
ParentConstraint constraint = null)
{
Assert.IsTrue(!constraint || target == constraint.transform);
if (!constraint)
{
if (!parentSource) return null;
constraint = target.gameObject.GetOrAddComponent<ParentConstraint>();
}
// 清空已有约束
constraint.constraintActive = false;
for (int i = constraint.sourceCount - 1; i >= 0; i--)
{
constraint.RemoveSource(i);
}
// 无约束
if (!parentSource) return constraint;
// 设置新约束
constraint.AddSource(new ConstraintSource
{
sourceTransform = parentSource,
weight = 1,
});
// 设置 Position offset
var positionOffset = parentSource.InverseTransformPoint(target.position);
constraint.SetTranslationOffset(0, positionOffset);
// 设置 Rotation offset
var localForward = parentSource.InverseTransformDirection(target.forward);
var localUpward = parentSource.InverseTransformDirection(target.up);
var rotationOffset = Quaternion.LookRotation(localForward, localUpward).eulerAngles;
constraint.SetRotationOffset(0, rotationOffset);
// 激活约束
constraint.constraintActive = true;
return constraint;
}
}
}

View File

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

View File

@ -0,0 +1,21 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit
{
public static class GameObjectExtensions
{
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
return gameObject.TryGetComponent<T>(out var t) ? t : gameObject.AddComponent<T>();
}
public static T RemoveComponent<T>(this GameObject gameObject) where T : Component
{
var t = gameObject.GetComponent<T>();
if (t is null) return null;
Object.Destroy(t);
return t;
}
}
}

View File

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

View File

@ -8,10 +8,35 @@ namespace BITKit
public class LocationAdditiveElement : MonoBehaviour
{
[SerializeField] private LocationAdditive locationAdditive;
[SerializeField] private Vector3 positionWeight = Vector3.one;
[SerializeField] private Vector3 eulerWeight = Vector3.one;
private Transform Transform;
private void Start()
{
Transform = transform;
}
private void Update()
{
locationAdditive.AddPosition(transform.localPosition);
locationAdditive.AddEuler(transform.localEulerAngles);
var localPosition = Transform.localPosition;
var localEulerAngles = Transform.localEulerAngles;
//locationAdditive.AddPosition(transform.localPosition);
//locationAdditive.AddEuler(transform.localEulerAngles);
locationAdditive.AddPosition(
new Vector3
{
x = localPosition.x * positionWeight.x,
y = localPosition.y * positionWeight.y,
z = localPosition.z * positionWeight.z
});
locationAdditive.AddEuler(
new Vector3
{
x = localEulerAngles.x * eulerWeight.x,
y = localEulerAngles.y * eulerWeight.y,
z = localEulerAngles.z * eulerWeight.z
});
}
}
}

View File

@ -9,7 +9,7 @@ using UnityEngine;
namespace BITKit.Net.Http
{
[CustomType(typeof(IHttpListenerService))]
public class UnityBasedHttpListenerService : EntityComponent,IHttpListenerService
public class UnityBasedHttpListenerService : EntityBehavior,IHttpListenerService
{
[SerializeField] private int port = 8080;
[SerializeField] private bool autoStart = true;

View File

@ -24,12 +24,15 @@ namespace BITKit.Physics
[SerializeField] private Optional<ConfigurableJointMotion> overrideMotion;
[SerializeField] private Optional<ConfigurableJointMotion> overrideAngularMotion;
private void Start()
{
foreach (var x in jointConfigures)
{
x.InitialRotation=x.animate.localRotation;
x.InitialRotation= x.animate.localRotation;
if (x.animate.localRotation != x.joint.transform.localRotation)
{
BIT4Log.Log<PhysicsBasedAnimation>($"{x.animate.name}初始旋转与关节旋转不一致,将会导致动画不正确");
}
}
}
private void FixedUpdate()
@ -45,12 +48,10 @@ namespace BITKit.Physics
{
jointConfigure.joint.angularXDrive = drive;
jointConfigure.joint.angularYZDrive = drive;
// jointConfigure.joint.targetRotation =
// Quaternion.Lerp(
// Quaternion.identity,
// Quaternion.Inverse(jointConfigure.animate.localRotation) * jointConfigure.InitialRotation,
// Blend
// );
jointConfigure.joint.xDrive = drive;
jointConfigure.joint.yDrive = drive;
jointConfigure.joint.zDrive = drive;
jointConfigure.joint.targetRotation = Quaternion.Inverse(jointConfigure.animate.localRotation) *
jointConfigure.InitialRotation;
jointConfigure.joint.targetPosition = jointConfigure.animate.localPosition;

View File

@ -9,6 +9,7 @@ namespace BITKit
{
public static async UniTask AddForceAtPositionAsync(this Rigidbody rigidbody, Vector3 force, Vector3 position,ForceMode forceMode=ForceMode.Force)
{
if (rigidbody is null) return;
await UniTask.DelayFrame(8);
try
{

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d500662d808c54d45abc4ec1a483b103
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,3 @@
{
"name": "BITKit.RendererPipeline"
}

View File

@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7eea6c92d884a5547a216347c599c670
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,49 @@
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace BITKit.Rendering
{
public class RenderWeaponsLastFeature : ScriptableRendererFeature
{
class RenderWeaponsLastPass : ScriptableRenderPass
{
private RenderQueueType renderQueueType;
private FilteringSettings filteringSettings;
public RenderWeaponsLastPass(RenderQueueType renderQueueType)
{
this.renderQueueType = renderQueueType;
this.filteringSettings = new FilteringSettings(){renderQueueRange = RenderQueueRange.all};
}
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cmd = CommandBufferPool.Get();
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
var sortFlags = renderingData.cameraData.defaultOpaqueSortFlags;
var drawSettings = CreateDrawingSettings(ShaderTagId.none, ref renderingData, sortFlags);
context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filteringSettings);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}
RenderWeaponsLastPass renderWeaponsLastPass;
public override void Create()
{
renderWeaponsLastPass = new RenderWeaponsLastPass(RenderQueueType.Opaque);
}
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
renderer.EnqueuePass(renderWeaponsLastPass);
}
}
}

View File

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

View File

@ -0,0 +1,28 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit.UX
{
public sealed class UGUIPanelComponent : MonoBehaviour
{
[SerializeReference, SubclassSelector] private IUXPanel panel;
[SerializeField] private RectTransform rectTransform;
private void Start()
{
panel.OnEntry += OnEntry;
panel.OnExit += OnExit;
OnExit();
}
private void OnExit()
{
rectTransform.gameObject.SetActive(false);
}
private void OnEntry()
{
rectTransform.gameObject.SetActive(true);
}
}
}

View File

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

View File

@ -134,6 +134,13 @@ namespace BITKit
protected static void FillDefaultInspector(VisualElement container, SerializedObject serializedObject, bool hideScript)
{
container.Clear();
if (serializedObject.targetObject is null)
{
var label = container.Create<Label>();
label.text = "Null";
return;
}
var property = serializedObject.GetIterator();
if (!property.NextVisible(true)) return; // Expand first child.
do

View File

@ -24,9 +24,38 @@ namespace BITKit
{
return float.IsNaN(self.x) || float.IsNaN(self.y) || float.IsNaN(self.z) || float.IsNaN(self.w);
}
public static Quaternion AlignRotation(Quaternion rotation, float angleIncrement)
{
var eulerAngles = rotation.eulerAngles;
eulerAngles.x = Mathf.Round(eulerAngles.x / angleIncrement) * angleIncrement;
eulerAngles.y = Mathf.Round(eulerAngles.y / angleIncrement) * angleIncrement;
eulerAngles.z = Mathf.Round(eulerAngles.z / angleIncrement) * angleIncrement;
return Quaternion.Euler(eulerAngles);
}
}
public static partial class MathV
{
// 对于 Vector3
public static Vector3 AlignRotation(Vector3 eulerAngles, float angleIncrement)
{
eulerAngles.x = Mathf.Round(eulerAngles.x / angleIncrement) * angleIncrement;
eulerAngles.y = Mathf.Round(eulerAngles.y / angleIncrement) * angleIncrement;
eulerAngles.z = Mathf.Round(eulerAngles.z / angleIncrement) * angleIncrement;
return eulerAngles;
}
public static Vector3 AlignToGrid(Vector3 position, float gridSize)
{
var x = Mathf.Round(position.x / gridSize) * gridSize;
var y = Mathf.Round(position.y / gridSize) * gridSize;
var z = Mathf.Round(position.z / gridSize) * gridSize;
return new Vector3(x, y, z);
}
private static float CalculateMaxSpeed(this Vector2 direction)
{
var angle = Vector2.Angle(Vector2.right, direction);

View File

@ -16,22 +16,47 @@ namespace BITKit
{
pool = new ObjectPool<T>(Spawn, OnGet, OnReturn, OnDestroy, maxSize: 16);
}
[Header(Constant.Header.Settings)]
[SerializeField] private int defaultCapacity = 16;
[Header(Constant.Header.Prefabs)]
public T prefab;
[SerializeField] private T prefab;
[Header(Constant.Header.Gameobjects)]
public Transform root;
[SerializeField] private Transform root;
private ObjectPool<T> pool;
private readonly List<T> _list=new();
public T Get(T element = null, Transform _root = null)
{
if (_list.Count == defaultCapacity)
{
var next = _list[0];
next.gameObject.SetActive(false);
_list.RemoveAt(0);
_list.Add(next);
next.gameObject.SetActive(true);
return next;
}
if (element is not null)
prefab = element;
if (_root is not null)
root = _root;
return pool.Get();
var instance = pool.Get();
_list.Add(instance);
return instance;
}
public void Return(T element)
{
pool.Release(element);
_list.Remove(element);
}
public void Return(T element) => pool.Release(element);
private T Spawn() => Object.Instantiate(prefab, root);
private void OnGet(T element) => element.gameObject.SetActive(true);
private void OnReturn(T element) => element.gameObject.SetActive(false);

View File

@ -179,6 +179,14 @@ namespace BITKit
public Vector3 position;
public Vector3 forward;
public Quaternion rotation;
public Location(Vector3 position, Quaternion rotation)
{
this.position = position;
this.rotation = rotation;
this.forward = rotation * Vector3.forward;
}
public Location Set(Vector3 value)
{
position = value;

View File

@ -1,5 +1,6 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using BITKit;
using UnityEngine.Events;
@ -22,13 +23,14 @@ namespace BITKit
sinleton = this;
DI.Register(this);
}
public Transform Spawn(VFXMessage message)
public Transform Spawn(RaycastHit hit, params string[] keyWords)
{
if (Data.TryGetValue<Transform>(message.path, out var vfx))
return Spawn(new Location()
{
return Instantiate(vfx, message.location, message.location);
}
return null;
position = hit.point,
rotation = Quaternion.LookRotation(hit.normal),
forward = hit.normal,
}, keyWords);
}
public Transform Spawn(Location location, params string[] keyWords)
{

View File

@ -4,7 +4,8 @@
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:75469ad4d38634e559750d17036d5f7c",
"GUID:709caf8d7fb6ef24bbba0ab9962a3ad0"
"GUID:709caf8d7fb6ef24bbba0ab9962a3ad0",
"GUID:7efac18f239530141802fb139776f333"
],
"includePlatforms": [],
"excludePlatforms": [],

View File

@ -1,6 +1,7 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using UnityEngine;
using BITKit.Entities;
using BITKit.Events;
@ -23,7 +24,7 @@ namespace BITKit.Vehicles
public WheelType wheelType;
}
public sealed class Vehicle : MonoBehaviour
public sealed class Vehicle : EntityBehavior
{
[Header(Constant.Header.Settings)] public float maxMotorTorque = 64;
[SerializeField] private float maxSteeringAngle = 45;
@ -36,6 +37,9 @@ namespace BITKit.Vehicles
[SerializeField]
private new Rigidbody rigidbody;
[SerializeField] private GameObject[] objects;
[SerializeField] private GameObject[] destroyedObjects;
[SerializeField] private Transform driveAnchor;
[Header(Constant.Header.Gameobjects)]
@ -52,8 +56,30 @@ namespace BITKit.Vehicles
private float horizontal;
private bool isBraking;
private readonly ValidHandle highSpeedHandle = new();
private IEntity _entity;
private void Start()
private IUnityEntity _unityEntity;
[Inject]
private IHealth _health;
public override void OnAwake()
{
base.OnAwake();
_health.OnSetAlive += OnSetAlive;
}
private void OnSetAlive(bool obj)
{
foreach (var x in objects)
{
x.SetActive(obj);
}
foreach (var x in destroyedObjects)
{
x.SetActive(!obj);
}
}
public override void OnStart()
{
highSpeedHandle.AddListener(x =>
{
@ -69,8 +95,7 @@ namespace BITKit.Vehicles
});
highSpeedHandle.Invoke();
}
private void Update()
public override void OnUpdate(float deltaTime)
{
var torque = maxMotorTorque *(optionalVertical.Allow ? optionalVertical.Value : vertical);
var steel =maxSteeringAngle * (optionalHorizontal.Allow ? optionalHorizontal.Value : horizontal);

8
Src/Unity/Shader.meta Normal file
View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 166cf7fe9f1842d4582528110079275d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,62 @@
// SomeShader.shader
Shader "Custom/AlwaysOnTopURP"
{
Properties
{
_BaseMap ("Texture", 2D) = "white" {}
_Color ("Color", Color) = (1,1,1,1)
}
SubShader
{
Tags { "RenderType"="Opaque" "RenderQueue"="Geometry+1000" }
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
ZTest Always
Pass
{
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_fragment _ALPHAPREMULTIPLY_ON
#pragma multi_compile_fragment _ALPHAMODULATE_ON
#pragma multi_compile_fragment _ALPHATEST_ON
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct Attributes
{
float4 positionOS : POSITION;
float2 uv : TEXCOORD0;
};
struct Varyings
{
float2 uv : TEXCOORD0;
float4 positionCS : SV_POSITION;
};
TEXTURE2D(_BaseMap);
SAMPLER(sampler_BaseMap);
float4 _BaseMap_ST;
float4 _Color;
Varyings vert(Attributes IN)
{
Varyings OUT;
OUT.uv = TRANSFORM_TEX(IN.uv, _BaseMap);
OUT.positionCS = TransformObjectToHClip(IN.positionOS.xyz);
return OUT;
}
half4 frag(Varyings IN) : SV_Target
{
half4 color = SAMPLE_TEXTURE2D(_BaseMap, sampler_BaseMap, IN.uv) * _Color;
return color;
}
ENDHLSL
}
}
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: a795400604734dc4681ca197360b4dac
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

Before

Width:  |  Height:  |  Size: 180 KiB

After

Width:  |  Height:  |  Size: 180 KiB

View File

@ -0,0 +1,64 @@
Shader "Custom/WireframeURP"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_LineColor("Line Color", Color) = (1, 1, 1, 1)
_BGColor("Background Color", Color) = (0, 0, 0, 0)
_LineWidth("Line Width", Range(0,0.1)) = 0.005
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
Name "Wireframe"
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
struct appdata
{
float4 vertex : POSITION;
float3 barycentric : TEXCOORD0; // Barycentric coordinates for wireframe
};
struct v2f
{
float2 uv : TEXCOORD0;
float3 barycentric : TEXCOORD1;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _LineColor;
float4 _BGColor;
float _LineWidth;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.barycentric.xy;
o.barycentric = v.barycentric;
return o;
}
half4 frag (v2f i) : SV_Target
{
half3 bary = i.barycentric;
bary = fwidth(bary) * _LineWidth + bary;
half mask = step(1, abs(bary.x) + abs(bary.y) + abs(bary.z));
half4 col = lerp(_LineColor, _BGColor, mask);
return col;
}
ENDCG
}
}
}

View File

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 91a3254e8d6044d498e07f2ae66f01e0
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@ -14,7 +14,6 @@ namespace BITKit
public class CinemachineHelper : MonoBehaviour
{
internal static CinemachineHelper Singleton { get; private set; }
[SerializeReference, SubclassSelector] public References ads;
public float Ads { get; private set; }
public CinemachineBrain brain;
private void Awake()
@ -24,13 +23,9 @@ namespace BITKit
private void FixedUpdate()
{
var playerConfig = Data.Get<PlayerConfig>();
var currentActive = brain.ActiveVirtualCamera as CinemachineVirtualCamera;
if (currentActive is not null && playerConfig is not null)
{
var currentFov = currentActive.m_Lens.FieldOfView;
Ads = currentFov / playerConfig.Fov;
}
if (brain.ActiveVirtualCamera is not CinemachineVirtualCamera currentActive) return;
var currentFov = currentActive.m_Lens.FieldOfView;
Ads = currentFov / PlayerConfig.Singleton.Fov;
}
}
}

Some files were not shown because too many files have changed in this diff Show More