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

@@ -11,19 +11,37 @@ using UnityEngine;
public class Character : MonoBehaviour
{
public bool isActivePlayer;
public Character root;
private InputToMovement inputToMovement;
private CharacterController2D characterController2D;
[SerializeField]
private float dissolveSpeed = 0.05f;
[SerializeField]
private Transform spawnPosition;
public Character root;
#region Components
private new Collider2D collider;
#endregion
#region Inspector
[SerializeField] private float dissolveSpeed = 0.05f;
[SerializeField] private Transform spawnPosition;
[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();
private static readonly int DissolveAmount = Shader.PropertyToID( "_DissolveAmount" );
private IEnumerator Start()
{
yield return new WaitForSeconds( 0.5f );
@@ -40,21 +58,32 @@ public class Character : MonoBehaviour
private void OnEnable()
{
inputToMovement = GetComponent<InputToMovement>();
characterController2D = GetComponent<CharacterController2D>();
GetComponent<InputToMovement>();
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;
// characterController2D.enabled = true;
this.root = prefab;
root = prefab;
isActivePlayer = true;
Killed += character => root.spawnedObjects.Remove( character );
}
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" );
return;
@@ -71,33 +100,65 @@ public class Character : MonoBehaviour
private void SpawnNew()
{
var newPlayer = Instantiate( root , spawnPosition.position , Quaternion.identity, parentForNew );
var newPlayer = Instantiate( root , spawnPosition.position , Quaternion.identity , parentForNew );
newPlayer.Init( root );
root.spawnedObjects.Add( newPlayer );
Spawned?.Invoke( newPlayer );
}
public void Dissolve()
public void Eat()
{
var target = FindNearestSpawned();
var target = FindNearestSpawned( eatRange );
if ( target == null )
return;
var size = target.transform.transform.localScale;
size.z = 0;
transform.localScale += size;
target.DissolveSelf();
}
public void DissolveSelf() { StartCoroutine( DissolveRoutine() ); }
private Character FindNearestSpawned()
private Character FindNearestSpawned( float range )
{
Character closest = null;
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 )
{
if ( spawnedObject == this )
continue;
var distance = math.distance( spawnedObject.transform.position , transform.position );
if ( distance > 2.5f )
if ( distance > range )
continue;
if ( closest != null
@@ -107,6 +168,7 @@ public class Character : MonoBehaviour
closest = spawnedObject;
closestDistance = distance;
}
*/
return closest;
}
@@ -118,11 +180,33 @@ public class Character : MonoBehaviour
while ( value < 1 )
{
value += dissolveSpeed;
mat.SetFloat( "_DissolveAmount" , value );
mat.SetFloat( DissolveAmount , value );
yield return null;
}
root.spawnedObjects.Remove( this );
Killed?.Invoke( this );
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;
// ReSharper disable once InvalidXmlDocComment
// ReSharper disable InvalidXmlDocComment
/// <summary>
/// The script from <see cref="https://github.com/Brackeys/2D-Character-Controller"/>
/// </summary>
public class CharacterController2D : MonoBehaviour
{
[SerializeField] private float m_JumpForce = 400f; // 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 m_MovementSmoothing = .05f; // How much to smooth out the movement
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
[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
[SerializeField] private float jumpForce = 50f; // Amount of force added when the player jumps.
[Range( 0 , .3f )] [SerializeField] private float 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 LayerMask 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
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 bool m_FacingRight = true; // For determining which way the player is currently facing.
private Vector3 m_Velocity = Vector3.zero;
private bool m_Grounded;// Whether or not the player is grounded.
private Rigidbody2D m_Rigidbody2D;
private CompositeCollider2D compositeCollider;
private Vector3 m_Velocity = Vector3.zero;
[Header("Events")]
[Space]
[Serializable] public class BoolEvent : UnityEvent<bool> { }
public UnityEvent OnLandEvent;
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
compositeCollider = GetComponent<CompositeCollider2D>();
}
[System.Serializable]
public class BoolEvent : UnityEvent<bool> { }
private Collider2D[] colliders = new Collider2D[10];
public BoolEvent OnCrouchEvent;
private bool m_wasCrouching = false;
private void FixedUpdate()
{
m_Grounded = false;
private void Awake()
{
m_Rigidbody2D = GetComponent<Rigidbody2D>();
Array.Clear( colliders , 0 , colliders.Length );
var bounds = compositeCollider.bounds;
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)
OnLandEvent = new UnityEvent();
foreach ( Collider2D c in colliders )
{
if ( c == null )
continue;
if (OnCrouchEvent == null)
OnCrouchEvent = new BoolEvent();
}
if ( c.gameObject == gameObject )
continue;
private void FixedUpdate()
{
bool wasGrounded = m_Grounded;
m_Grounded = false;
if ( c.transform.IsChildOf( transform ) )
continue;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
if (!wasGrounded)
OnLandEvent.Invoke();
}
}
}
if ( Physics2D.Distance( compositeCollider , c ).distance > groundedRadius )
continue;
m_Grounded = true;
}
}
public void Move(float move, bool crouch, bool jump)
{
// If crouching, check to see if the character can stand up
if (!crouch)
{
// If the character has a ceiling preventing them from standing up, keep them crouching
if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
{
crouch = true;
}
}
public void Move( float move , bool jump )
{
//only control the player if grounded or airControl is turned on
if ( m_Grounded || airControl )
{
// Move the character by finding the target velocity
var velocity = m_Rigidbody2D.velocity;
Vector3 targetVelocity = new Vector2( move * 10f , velocity.y );
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// And then smoothing it out and applying it to the character
m_Rigidbody2D.velocity = Vector3.SmoothDamp( velocity , targetVelocity , ref m_Velocity , movementSmoothing );
}
// If crouching
if (crouch)
{
if (!m_wasCrouching)
{
m_wasCrouching = true;
OnCrouchEvent.Invoke(true);
}
// If the player should jump...
if ( !m_Grounded || !jump )
return;
// Reduce the speed by the crouchSpeed multiplier
move *= m_CrouchSpeed;
// Add a vertical force to the player.
m_Grounded = false;
m_Rigidbody2D.AddForce( new Vector2( 0f , jumpForce ) );
}
// Disable one of the colliders when crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = false;
} else
{
// Enable the collider when not crouching
if (m_CrouchDisableCollider != null)
m_CrouchDisableCollider.enabled = true;
private void OnDrawGizmosSelected()
{
if ( compositeCollider == null )
return;
if (m_wasCrouching)
{
m_wasCrouching = false;
OnCrouchEvent.Invoke(false);
}
}
var bounds = compositeCollider.bounds;
var size = new Vector2( bounds.size.x + groundedRadius , bounds.size.y + groundedRadius );
// Move the character by finding the target velocity
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;
}
}
Gizmos.DrawWireCube( bounds.center , size );
}
}

View File

@@ -1,7 +1,3 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
@@ -9,9 +5,9 @@ public class DissolveCollidersExceptPlayer : MonoBehaviour
{
private void OnTriggerEnter2D( Collider2D col )
{
if ( !col.TryGetComponent( out Character character ) )
if ( !col.TryGetComponent( out Character character ) )
return;
if ( character.isActivePlayer )
return;

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

View File

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