Movement & Attaching etc.

also cleanup
This commit is contained in:
OMGeeky
2022-05-22 01:56:22 +02:00
parent 308f1d91f3
commit 6ffa65dcb1
13 changed files with 4085 additions and 360 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -52,7 +52,7 @@ Material:
m_Scale: {x: 1, y: 1} m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0} m_Offset: {x: 0, y: 0}
- _MainTex: - _MainTex:
m_Texture: {fileID: 2800000, guid: 0e141e3371de4a745962f5fa234ae937, type: 3} m_Texture: {fileID: 2800000, guid: 376a6e51f699053478a14fdfefd7f930, type: 3}
m_Scale: {x: 1, y: 1} m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0} m_Offset: {x: 0, y: 0}
- _MetallicGlossMap: - _MetallicGlossMap:
@@ -60,7 +60,7 @@ Material:
m_Scale: {x: 1, y: 1} m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0} m_Offset: {x: 0, y: 0}
- _NormalMap: - _NormalMap:
m_Texture: {fileID: 2800000, guid: 9809c99ad563f144089e38062b03db98, type: 3} m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1} m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0} m_Offset: {x: 0, y: 0}
- _OcclusionMap: - _OcclusionMap:
@@ -87,7 +87,7 @@ Material:
- _GlossyReflections: 1 - _GlossyReflections: 1
- _Metallic: 0 - _Metallic: 0
- _Mode: 0 - _Mode: 0
- _NormalStrenght: 1.5 - _NormalStrenght: 0
- _OcclusionStrength: 1 - _OcclusionStrength: 1
- _Parallax: 0.02 - _Parallax: 0.02
- _SmoothnessTextureChannel: 0 - _SmoothnessTextureChannel: 0

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,25 @@
using Cinemachine;
using UnityEngine;
public class CameraController : MonoBehaviour
{
[SerializeField] private Character root;
[SerializeField] private CinemachineVirtualCamera vCam;
private void OnEnable()
{
if ( vCam == null )
vCam = GetComponent<CinemachineVirtualCamera>();
root.Spawned += RootOnSpawned;
}
private void RootOnSpawned( Character obj )
{
var objTransform = obj.transform;
vCam.Follow = objTransform;
vCam.LookAt = objTransform;
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e7de0477c4e04c24ad762210a7f4adf6
timeCreated: 1653169076

View File

@@ -14,16 +14,34 @@ public class Character : MonoBehaviour
public Character root; public Character root;
#region Components
private InputToMovement inputToMovement; private new Collider2D collider;
private CharacterController2D characterController2D;
[SerializeField] #endregion
private float dissolveSpeed = 0.05f;
[SerializeField] #region Inspector
private Transform spawnPosition;
[SerializeField] private float dissolveSpeed = 0.05f;
[SerializeField] private Transform spawnPosition;
[SerializeField] private Transform parentForNew; [SerializeField] private Transform parentForNew;
[SerializeField] private LayerMask findLayerMask;
[SerializeField] private float eatRange = 2.5f;
[SerializeField] private float attachRange = .5f;
#endregion
#region Events
public event Action<Character> Killed;
public event Action<Character> Spawned;
#endregion
public List<Character> spawnedObjects = new(); public List<Character> spawnedObjects = new();
private static readonly int DissolveAmount = Shader.PropertyToID( "_DissolveAmount" );
private IEnumerator Start() private IEnumerator Start()
{ {
yield return new WaitForSeconds( 0.5f ); yield return new WaitForSeconds( 0.5f );
@@ -40,21 +58,32 @@ public class Character : MonoBehaviour
private void OnEnable() private void OnEnable()
{ {
inputToMovement = GetComponent<InputToMovement>(); GetComponent<InputToMovement>();
characterController2D = GetComponent<CharacterController2D>(); GetComponent<CharacterController2D>();
collider = GetComponent<Collider2D>();
if ( root != null )
{
Spawned -= OnSpawned;
Spawned += OnSpawned;
}
} }
public void Init( Character prefab ) private void OnSpawned( Character c ) { root.CallSpawned( c ); }
private void CallSpawned( Character character ) { Spawned?.Invoke( character ); }
private void Init( Character prefab )
{ {
// inputToMovement.enabled = true; // inputToMovement.enabled = true;
// characterController2D.enabled = true; // characterController2D.enabled = true;
this.root = prefab; root = prefab;
isActivePlayer = true; isActivePlayer = true;
Killed += character => root.spawnedObjects.Remove( character );
} }
public void KillSelf() public void KillSelf()
{ {
if ( math.distance( transform.position , Vector3.zero ) < 2 ) if ( math.distance( transform.position , spawnPosition.position ) < 2 )
{ {
Debug.Log( "Cant restart here, too near to spawn" ); Debug.Log( "Cant restart here, too near to spawn" );
return; return;
@@ -71,33 +100,65 @@ public class Character : MonoBehaviour
private void SpawnNew() private void SpawnNew()
{ {
var newPlayer = Instantiate( root , spawnPosition.position , Quaternion.identity, parentForNew ); var newPlayer = Instantiate( root , spawnPosition.position , Quaternion.identity , parentForNew );
newPlayer.Init( root ); newPlayer.Init( root );
root.spawnedObjects.Add( newPlayer ); root.spawnedObjects.Add( newPlayer );
Spawned?.Invoke( newPlayer );
} }
public void Dissolve() public void Eat()
{ {
var target = FindNearestSpawned(); var target = FindNearestSpawned( eatRange );
if ( target == null ) if ( target == null )
return; return;
var size = target.transform.transform.localScale;
size.z = 0;
transform.localScale += size;
target.DissolveSelf(); target.DissolveSelf();
} }
public void DissolveSelf() { StartCoroutine( DissolveRoutine() ); } public void DissolveSelf() { StartCoroutine( DissolveRoutine() ); }
private Character FindNearestSpawned() private Character FindNearestSpawned( float range )
{ {
Character closest = null; Character closest = null;
float closestDistance = float.MaxValue; float closestDistance = float.MaxValue;
var t = transform;
var localScale = t.localScale;
Collider2D[] colliders = new Collider2D[50];
Physics2D.OverlapBoxNonAlloc( point: t.position
, size: new Vector2( localScale.x + range , localScale.y + range )
, angle: t.rotation.eulerAngles.z
, results: colliders
, layerMask: findLayerMask );
foreach ( Collider2D coll in colliders )
{
if ( !coll.TryGetComponent( out Character character ) )
continue;
if ( character == this )
continue;
var distance = Physics2D.Distance( collider , coll ).distance;
if ( distance >= closestDistance )
continue;
closest = character;
closestDistance = distance;
}
/*
foreach ( Character spawnedObject in root.spawnedObjects ) foreach ( Character spawnedObject in root.spawnedObjects )
{ {
if ( spawnedObject == this ) if ( spawnedObject == this )
continue; continue;
var distance = math.distance( spawnedObject.transform.position , transform.position ); var distance = math.distance( spawnedObject.transform.position , transform.position );
if ( distance > 2.5f ) if ( distance > range )
continue; continue;
if ( closest != null if ( closest != null
@@ -107,6 +168,7 @@ public class Character : MonoBehaviour
closest = spawnedObject; closest = spawnedObject;
closestDistance = distance; closestDistance = distance;
} }
*/
return closest; return closest;
} }
@@ -118,11 +180,33 @@ public class Character : MonoBehaviour
while ( value < 1 ) while ( value < 1 )
{ {
value += dissolveSpeed; value += dissolveSpeed;
mat.SetFloat( "_DissolveAmount" , value ); mat.SetFloat( DissolveAmount , value );
yield return null; yield return null;
} }
root.spawnedObjects.Remove( this ); Killed?.Invoke( this );
Destroy( gameObject ); Destroy( gameObject );
} }
public void Attach()
{
var target = FindNearestSpawned( attachRange );
if ( target == null )
return;
target.transform.parent = transform;
RemovePlayerComponentsFromTarget( target );
}
private static void RemovePlayerComponentsFromTarget( Character target )
{
var targetRb = target.GetComponent<Rigidbody2D>();
var targetCol = target.GetComponent<CompositeCollider2D>();
var targetController = target.GetComponent<CharacterController2D>();
var targetInput = target.GetComponent<InputToMovement>();
Destroy( targetInput );
Destroy( targetController );
Destroy( targetCol );
Destroy( targetRb );
}
} }

View File

@@ -1,150 +1,98 @@
using UnityEngine; using System;
using UnityEngine;
using UnityEngine.Events; using UnityEngine.Events;
// ReSharper disable once InvalidXmlDocComment
// ReSharper disable InvalidXmlDocComment // ReSharper disable InvalidXmlDocComment
/// <summary> /// <summary>
/// The script from <see cref="https://github.com/Brackeys/2D-Character-Controller"/> /// The script from <see cref="https://github.com/Brackeys/2D-Character-Controller"/>
/// </summary> /// </summary>
public class CharacterController2D : MonoBehaviour public class CharacterController2D : MonoBehaviour
{ {
[SerializeField] private float m_JumpForce = 400f; // Amount of force added when the player jumps. [SerializeField] private float jumpForce = 50f; // Amount of force added when the player jumps.
[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100% [Range( 0 , .3f )] [SerializeField] private float movementSmoothing = .05f;// How much to smooth out the movement
[Range(0, .3f)] [SerializeField] private float m_MovementSmoothing = .05f; // How much to smooth out the movement [SerializeField] private bool airControl = true; // Whether or not a player can steer while jumping;
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping; [SerializeField] private LayerMask whatIsGround; // A mask determining what is ground to the character
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character [Range( 0 , 2 )] [SerializeField] private float groundedRadius = 1.5f; // Radius of the overlap circle to determine if grounded
[SerializeField] private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
[SerializeField] private Transform m_CeilingCheck; // A position marking where to check for ceilings
[SerializeField] private Collider2D m_CrouchDisableCollider; // A collider that will be disabled when crouching
[Range(0,2)][SerializeField]private float k_GroundedRadius = 1.5f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded. private bool m_Grounded;// Whether or not the player is grounded.
const float k_CeilingRadius = .2f; // Radius of the overlap circle to determine if the player can stand upf private Rigidbody2D m_Rigidbody2D;
private Rigidbody2D m_Rigidbody2D; private CompositeCollider2D compositeCollider;
private bool m_FacingRight = true; // For determining which way the player is currently facing. private Vector3 m_Velocity = Vector3.zero;
private Vector3 m_Velocity = Vector3.zero;
[Header("Events")] [Serializable] public class BoolEvent : UnityEvent<bool> { }
[Space]
public UnityEvent OnLandEvent; private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
compositeCollider = GetComponent<CompositeCollider2D>();
}
[System.Serializable] private Collider2D[] colliders = new Collider2D[10];
public class BoolEvent : UnityEvent<bool> { }
public BoolEvent OnCrouchEvent; private void FixedUpdate()
private bool m_wasCrouching = false; {
m_Grounded = false;
private void Awake() Array.Clear( colliders , 0 , colliders.Length );
{ var bounds = compositeCollider.bounds;
m_Rigidbody2D = GetComponent<Rigidbody2D>(); var size = new Vector2( bounds.size.x + groundedRadius , bounds.size.y + groundedRadius );
Physics2D.OverlapBoxNonAlloc( point: bounds.center
, size: size
, angle: 0
, results: colliders
, layerMask: whatIsGround );
if (OnLandEvent == null) foreach ( Collider2D c in colliders )
OnLandEvent = new UnityEvent(); {
if ( c == null )
continue;
if (OnCrouchEvent == null) if ( c.gameObject == gameObject )
OnCrouchEvent = new BoolEvent(); continue;
}
private void FixedUpdate() if ( c.transform.IsChildOf( transform ) )
{ continue;
bool wasGrounded = m_Grounded;
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground if ( Physics2D.Distance( compositeCollider , c ).distance > groundedRadius )
// This can be done using layers instead but Sample Assets will not overwrite your project settings. continue;
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++) m_Grounded = true;
{ }
if (colliders[i].gameObject != gameObject) }
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
public void Move(float move, bool crouch, bool jump) public void Move( float move , bool jump )
{ {
// If crouching, check to see if the character can stand up //only control the player if grounded or airControl is turned on
if (!crouch) if ( m_Grounded || airControl )
{ {
// If the character has a ceiling preventing them from standing up, keep them crouching // Move the character by finding the target velocity
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround)) var velocity = m_Rigidbody2D.velocity;
{ Vector3 targetVelocity = new Vector2( move * 10f , velocity.y );
crouch = true;
}
}
//only control the player if grounded or airControl is turned on // And then smoothing it out and applying it to the character
if (m_Grounded || m_AirControl) m_Rigidbody2D.velocity = Vector3.SmoothDamp( velocity , targetVelocity , ref m_Velocity , movementSmoothing );
{ }
// If crouching // If the player should jump...
if (crouch) if ( !m_Grounded || !jump )
{ return;
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// Reduce the speed by the crouchSpeed multiplier // Add a vertical force to the player.
move *= m_CrouchSpeed; m_Grounded = false;
m_Rigidbody2D.AddForce( new Vector2( 0f , jumpForce ) );
}
// Disable one of the colliders when crouching private void OnDrawGizmosSelected()
if (m_CrouchDisableCollider != null) {
m_CrouchDisableCollider.enabled = false; if ( compositeCollider == null )
} else return;
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
if (m_wasCrouching) var bounds = compositeCollider.bounds;
{ var size = new Vector2( bounds.size.x + groundedRadius , bounds.size.y + groundedRadius );
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
// Move the character by finding the target velocity Gizmos.DrawWireCube( bounds.center , size );
Vector3 targetVelocity = new Vector2(move * 10f, m_Rigidbody2D.velocity.y); }
// And then smoothing it out and applying it to the character
m_Rigidbody2D.velocity = Vector3.SmoothDamp(m_Rigidbody2D.velocity, targetVelocity, ref m_Velocity, m_MovementSmoothing);
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (m_Grounded && jump)
{
// Add a vertical force to the player.
m_Grounded = false;
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce));
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
} }

View File

@@ -1,7 +1,3 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine; using UnityEngine;

View File

@@ -0,0 +1,26 @@
using UnityEngine;
public static class GizmosExtended
{
public static void DrawCubeWithLocalSpace( Vector3 center , float size , Transform transform )
{
var s = new Vector3( size , size , -1 );
Gizmos.matrix = Matrix4x4.TRS( transform.TransformPoint( Vector3.zero ) , transform.rotation , transform.lossyScale );
Gizmos.DrawCube( Vector3.zero , Vector3.one + s );
// var pUR = (Vector2) center + new Vector2( size.x , size.y );
// var pUL = (Vector2) center + new Vector2( -size.x , size.y );
// var pDR = (Vector2) center + new Vector2( size.x , -size.y );
// var pDL = (Vector2) center + new Vector2( -size.x , -size.y );
}
}
public static class Vector2Extension
{
public static Vector2 Rotate( this Vector2 v , float degrees )
{
return Quaternion.Euler( 0 , 0 , degrees ) * v;
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6a664528b07c49c3a9778216301756d7
timeCreated: 1653155890

View File

@@ -1,5 +1,4 @@
using System.Collections; using System;
using System.Collections.Generic;
using UnityEngine; using UnityEngine;
@@ -10,29 +9,29 @@ public class InputToMovement : MonoBehaviour
private CharacterController2D controller2D; private CharacterController2D controller2D;
private Character character; private Character character;
void OnEnable() private void OnEnable()
{ {
controller2D = GetComponent<CharacterController2D>(); controller2D = GetComponent<CharacterController2D>();
character = GetComponent<Character>(); character = GetComponent<Character>();
// interactTimer = 0; // interactTimer = 0;
} }
// Update is called once per frame // Update is called once per frame
[SerializeField] [SerializeField] private float interactTimer;
private float interactTimer = 0; [SerializeField] private float interactThreshold = 1;
[SerializeField] [SerializeField] private float reloadTimer;
private float interactThreshold = 3; [SerializeField] private float reloadThreshold = 1;
[SerializeField] [SerializeField] private float attachTimer;
private float reloadTimer = 0; [SerializeField] private float attachThreshold = 1;
[SerializeField]
private float reloadThreshold = 1;
void Update() private void Update()
{ {
if ( !character.isActivePlayer ) if ( !character.isActivePlayer )
return; return;
// if ( controller2D == null ) // if ( controller2D == null )
// return; // return;
var horizontal = Input.GetAxis( "Horizontal" ); var horizontal = Input.GetAxis( "Horizontal" );
var jump = Input.GetButton( "Jump" ); var jump = Input.GetButton( "Jump" );
@@ -40,7 +39,7 @@ public class InputToMovement : MonoBehaviour
// var crouch = Input.GetButton( "Crouch" ); // var crouch = Input.GetButton( "Crouch" );
if ( horizontal != 0 || jump ) if ( horizontal != 0 || jump )
{ {
controller2D.Move( horizontal , false , jump ); controller2D.Move( horizontal , jump );
} }
var interact = Input.GetButton( "Interact" ); var interact = Input.GetButton( "Interact" );
@@ -58,6 +57,7 @@ public class InputToMovement : MonoBehaviour
character.KillSelf(); character.KillSelf();
interactTimer = 0; interactTimer = 0;
} }
var reload = Input.GetButton( "Reload" ); var reload = Input.GetButton( "Reload" );
if ( reload ) if ( reload )
{ {
@@ -70,8 +70,26 @@ public class InputToMovement : MonoBehaviour
if ( reloadTimer >= reloadThreshold ) if ( reloadTimer >= reloadThreshold )
{ {
character.Dissolve(); character.Eat();
reloadTimer = 0; reloadTimer = 0;
} }
var attach = Input.GetButton( "Attach" );
if ( attach )
{
attachTimer += Time.deltaTime;
}
else
{
attachTimer = 0;
}
if ( attachTimer >= attachThreshold )
{
character.Attach();
attachTimer = 0;
}
Console.WriteLine();
} }
} }

View File

@@ -517,4 +517,20 @@ InputManager:
type: 0 type: 0
axis: 0 axis: 0
joyNum: 0 joyNum: 0
- serializedVersion: 3
m_Name: Attach
descriptiveName:
descriptiveNegativeName:
negativeButton:
positiveButton: q
altNegativeButton:
altPositiveButton:
gravity: 1000
dead: 0.001
sensitivity: 1000
snap: 0
invert: 0
type: 0
axis: 0
joyNum: 0
m_UsePhysicalKeys: 1 m_UsePhysicalKeys: 1

View File

@@ -16,7 +16,7 @@ TagManager:
- Characters - Characters
- -
- -
- - MapIgnore
- -
- -
- -