Commit 665dc919 by alsunj

improve player movement

parent d4490503
......@@ -15,10 +15,10 @@ public class PlayerAnimator : NetworkBehaviour
private void Update()
{
if (!IsOwner)
{
return;
}
// if (!IsOwner)
// {
// return;
// }
_animator.SetBool(IS_WALKING, _playerController.IsWalking());
}
......
using System;
using Unity.Netcode;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Serialization;
public class PlayerController : NetworkBehaviour
{
[SerializeField] private PlayerInteractionSettings _playerInteractionSettings;
[SerializeField] private float _speed = 2f;
[SerializeField] private PlayerInteractionSettings playerInteractionSettings;
[SerializeField] private float speed = 2f;
[SerializeField] private InputReader _inputReader;
private Rigidbody _rb;
[SerializeField] private Camera _camera;
private Camera _camera;
public Vector3 offset = new Vector3(0, 7.4f, -6.4f);
public Vector3 eulerAngles = new Vector3(40.45f, 0, 0);
private bool _isWalking;
//camera public Vector3 eulerAngles = new Vector3(40.45f, 0, 0);
private Vector2 _movementInput;
public float fov = 60;
void Start()
public bool enableSprint = true;
public bool unlimitedSprint = false;
public float sprintSpeed = 7f;
public float sprintDuration = 5f;
public float sprintCooldown = .5f;
public float sprintFOV = 80f;
public float sprintFOVStepTime = 10f;
public float zoomStepTime = 5f;
public bool playerCanMove = true;
public float walkSpeed = 5f;
public bool _isWalking = false;
public float maxVelocityChange = 10f;
// Internal Variables
private bool _isSprinting = false;
private float _sprintRemaining;
private bool _isSprintCooldown = false;
private float _sprintCooldownReset;
// Internal Variables
private Vector3 _jointOriginalPos;
private float _timer = 0;
private float _walkingSoundTimer = 0;
private bool _isWalkingSoundCooldown = false;
private float _sprintingSoundTimer = 0;
private bool _isSprintingSoundCooldown = false;
private void OnEnable()
{
if (_inputReader != null)
{
_inputReader.MoveEvent += OnMove;
_inputReader.InteractEvent += OnInteract;
_inputReader.SprintEvent += OnSprint;
}
}
private void OnDisable()
{
if (_inputReader != null)
{
_inputReader.MoveEvent -= OnMove;
_inputReader.InteractEvent -= OnInteract;
_inputReader.SprintEvent -= OnSprint;
}
}
private void Start()
{
_camera = GetComponentInChildren<Camera>();
_inputReader.InitializeInput();
_rb = GetComponent<Rigidbody>();
_rb.isKinematic = false; // Ensure isKinematic is false
}
void Update()
private void OnSprint(bool state)
{
// if (!IsOwner)
// {
// return;
// }
_isSprinting = state;
}
if (Input.GetKeyDown(KeyCode.E))
private void OnMove(Vector2 movement)
{
CheckForInteractableCollision();
_movementInput = movement;
}
private void Update()
{
if (enableSprint)
{
if (_isSprinting && !_isSprintCooldown)
{
if (_isSprintingSoundCooldown)
{
// if flash is on cooldown, increase the timer
_sprintingSoundTimer += Time.deltaTime;
// if the timer is greater than the cooldown, refresh the cooldown boolean and reset the timer
if (_sprintingSoundTimer >= 0.3f)
{
_isSprintingSoundCooldown = false;
_sprintingSoundTimer = 0f;
}
}
if (!_isSprintingSoundCooldown)
{
_isSprintingSoundCooldown = true;
}
_camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, sprintFOV,
sprintFOVStepTime * Time.deltaTime);
// Drain sprint remaining while sprinting
if (!unlimitedSprint)
{
_sprintRemaining -= 1 * Time.deltaTime;
if (_sprintRemaining <= 0)
{
_isSprinting = false;
_isSprintCooldown = true;
}
}
}
else
{
// Regain sprint while not sprinting
_sprintRemaining = Mathf.Clamp(_sprintRemaining += 1 * Time.deltaTime, 0, sprintDuration);
_camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, fov, zoomStepTime * Time.deltaTime);
}
UpdateMovement();
// Handles sprint cooldown
// When sprint remaining == 0 stops sprint ability until hitting cooldown
if (_isSprintCooldown)
{
sprintCooldown -= 1 * Time.deltaTime;
if (sprintCooldown <= 0)
{
_isSprintCooldown = false;
}
}
else
{
sprintCooldown = _sprintCooldownReset;
}
}
}
private void UpdateMovement()
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical).normalized * _speed * Time.fixedDeltaTime;
if (movement != Vector3.zero)
#region Movement
if (playerCanMove)
{
// Use the input from _movementInput to determine movement
Vector3 targetVelocity = new Vector3(_movementInput.x, 0, _movementInput.y);
// Checks if player is walking and is grounded
if (targetVelocity.x != 0 || targetVelocity.z != 0)
{
_rb.MovePosition(transform.position + movement);
Debug.Log(movement);
Quaternion targetRotation = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, _speed);
_camera.transform.rotation = Quaternion.Slerp(_camera.transform.rotation,
targetRotation * Quaternion.Euler(eulerAngles), _speed);
_isWalking = true;
if (_isWalkingSoundCooldown)
{
// if flash is on cooldown, increase the timer
_walkingSoundTimer += Time.fixedDeltaTime;
// if the timer is greater than the cooldown, refresh the cooldown boolean and reset the timer
if (_walkingSoundTimer >= 0.5f)
{
_isWalkingSoundCooldown = false;
_walkingSoundTimer = 0f;
}
}
if (!_isWalkingSoundCooldown)
{
_isWalkingSoundCooldown = true;
}
}
else
{
_isWalking = false;
}
// All movement calculations while sprint is active
if (enableSprint && _isSprinting && _sprintRemaining > 0f && !_isSprintCooldown)
{
targetVelocity = transform.TransformDirection(targetVelocity) * sprintSpeed;
Vector3 velocity = _rb.linearVelocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
if (velocityChange.x != 0 || velocityChange.z != 0)
{
_isSprinting = true;
}
_rb.AddForce(velocityChange, ForceMode.VelocityChange);
}
// All movement calculations while walking
else
{
_isSprinting = false;
targetVelocity = transform.TransformDirection(targetVelocity) * walkSpeed;
Vector3 velocity = _rb.linearVelocity;
Vector3 velocityChange = (targetVelocity - velocity);
velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
velocityChange.y = 0;
_rb.AddForce(velocityChange, ForceMode.VelocityChange);
}
if (targetVelocity != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(targetVelocity);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.fixedDeltaTime);
}
}
UpdateCamera();
UpdateMovementBooleans();
#endregion
}
private void OnInteract()
{
Debug.Log("Interact");
CheckForInteractableCollision();
}
private void UpdateCamera()
{
_camera.transform.position = gameObject.transform.position + offset;
_camera.transform.localPosition = offset;
_camera.transform.localRotation = Quaternion.Euler(40.45f, 0, 0);
}
private void CheckForInteractableCollision()
{
Collider[] hitColliders = Physics.OverlapSphere(transform.position,
_playerInteractionSettings.interactableRadius,
_playerInteractionSettings.interactableLayer);
playerInteractionSettings.interactableRadius,
playerInteractionSettings.interactableLayer);
foreach (var hitCollider in hitColliders)
{
switch (hitCollider.GetComponent<IInteractable>())
......
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
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: 38046858527cd1b4fa2edbe312d75842, type: 3}
m_Name: InputReader
m_EditorClassIdentifier:
fileFormatVersion: 2
guid: fae963ae99ce6d14d8bbcd54becb58d7
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
......@@ -5,6 +5,7 @@ using UnityEngine.InputSystem;
[CreateAssetMenu(fileName = "InputReader", menuName = "Scriptable Objects/InputReader")]
public class InputReader : ScriptableObject, InputSystem_Actions.IPlayerActions, IInputHandler
{
private InputSystem_Actions inputActions;
public event Action<Vector2> MoveEvent;
public event Action<Vector2> LookEvent;
public event Action InteractEvent;
......@@ -13,6 +14,27 @@ public class InputReader : ScriptableObject, InputSystem_Actions.IPlayerActions,
public event Action<bool> CrouchEvent;
public event Action AttackEvent;
public void InitializeInput()
{
if (inputActions == null)
{
inputActions = new InputSystem_Actions();
inputActions.Player.SetCallbacks(this);
}
inputActions.Enable();
}
private void OnDisable()
{
if (inputActions != null)
{
inputActions.Disable();
inputActions.Player.RemoveCallbacks(this);
inputActions.Dispose();
}
}
public void OnMove(InputAction.CallbackContext context)
{
if (context.performed)
......@@ -21,7 +43,7 @@ public class InputReader : ScriptableObject, InputSystem_Actions.IPlayerActions,
}
else
{
MoveEvent?.Invoke(new Vector2(0, 0));
MoveEvent?.Invoke(Vector2.zero);
}
}
......
......@@ -152,7 +152,7 @@ Transform:
m_ConstrainProportionsScale: 0
m_Children:
- {fileID: 645337607}
m_Father: {fileID: 0}
m_Father: {fileID: 1623128584}
m_LocalEulerAnglesHint: {x: 0, y: 180, z: 0}
--- !u!65 &20099878
BoxCollider:
......@@ -1159,10 +1159,42 @@ PrefabInstance:
propertyPath: GlobalObjectIdHash
value: 1048055298
objectReference: {fileID: 0}
- target: {fileID: 3702991396873574320, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: fov
value: 74.36
objectReference: {fileID: 0}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: speed
value: 5
objectReference: {fileID: 0}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: walkSpeed
value: 10.14
objectReference: {fileID: 0}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: _inputReader
value:
objectReference: {fileID: 11400000, guid: fae963ae99ce6d14d8bbcd54becb58d7, type: 2}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: unlimitedSprint
value: 1
objectReference: {fileID: 0}
- target: {fileID: 4346266333506682639, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: playerInteractionSettings
value:
objectReference: {fileID: 11400000, guid: 1bc75bcaab451a44d8a71f0189dc90f8, type: 2}
- target: {fileID: 7039287367920326276, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: m_Name
value: Player
objectReference: {fileID: 0}
- target: {fileID: 7039287367920326276, guid: 702bb31d143eeaa4792be36b28160445, type: 3}
propertyPath: m_IsActive
value: 1
objectReference: {fileID: 0}
m_RemovedComponents: []
m_RemovedGameObjects: []
m_AddedGameObjects: []
......@@ -1355,7 +1387,8 @@ Transform:
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_ConstrainProportionsScale: 0
m_Children: []
m_Children:
- {fileID: 20099877}
m_Father: {fileID: 0}
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!1 &1687222682
......@@ -1375,7 +1408,7 @@ GameObject:
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
m_IsActive: 0
--- !u!114 &1687222683
MonoBehaviour:
m_ObjectHideFlags: 0
......@@ -1645,7 +1678,7 @@ GameObject:
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
m_IsActive: 0
--- !u!114 &1909091470
MonoBehaviour:
m_ObjectHideFlags: 0
......@@ -1775,7 +1808,6 @@ SceneRoots:
- {fileID: 1294522714}
- {fileID: 98077555}
- {fileID: 1623128584}
- {fileID: 20099877}
- {fileID: 1687222685}
- {fileID: 303522006}
- {fileID: 865924118}
......
......@@ -11,6 +11,9 @@ EditorBuildSettings:
- enabled: 1
path: Assets/Scenes/Scene.unity
guid: fb476371a58224b439cbcc569f3d86f0
- enabled: 1
path: Assets/_Game/Scenes/SC.unity
guid: 4bdbbb25aff08a54098c34d6f75b201b
m_configObjects:
com.unity.input.settings.actions: {fileID: -944628639613478452, guid: 052faaac586de48259a63d0c4782560b, type: 3}
m_UseUCBPForAssetBundles: 0
......@@ -25,7 +25,7 @@ EditorSettings:
m_AsyncShaderCompilation: 1
m_PrefabModeAllowAutoSave: 1
m_EnterPlayModeOptionsEnabled: 1
m_EnterPlayModeOptions: 0
m_EnterPlayModeOptions: 1
m_GameObjectNamingDigits: 1
m_GameObjectNamingScheme: 0
m_AssetNamingUsesSpace: 1
......
......@@ -945,7 +945,7 @@ PlayerSettings:
qnxGraphicConfPath:
apiCompatibilityLevel: 6
captureStartupLogs: {}
activeInputHandler: 2
activeInputHandler: 1
windowsGamepadBackendHint: 0
cloudProjectId: 3cd49368-e13d-4741-80b2-b4559fc6fe1b
framebufferDepthMemorylessMode: 0
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment