Skip to content
Snippets Groups Projects
Commit 0af2613b authored by Sofiane Lasri's avatar Sofiane Lasri
Browse files

Removed TPS controller

parent d643b514
No related branches found
No related tags found
No related merge requests found
fileFormatVersion: 2
guid: 66d090248a0748e4c813eb773890fe97
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterAnimation : MonoBehaviour
{
[Header("Character")]
public GameObject puppetMasterHeadBone;
private GameObject camera;
protected virtual void Start() {
if (transform.parent.GetComponent<PlayerMovement>() == null) {
Debug.LogWarning("L'animation controller doit être l'enfant du character controllers!", transform);
}
camera = GameObject.Find("Player Camera");
}
protected virtual void FixedUpdate() {
TurnHead();
}
void OnAnimatorMove(){
GetComponentInParent<PlayerMovement>().OnAnimatorMove();
}
private void TurnHead(){
var rotY = camera.transform.eulerAngles.y - transform.parent.transform.eulerAngles.y;
//rotY = (rotY > 180) ? rotY - 360 : rotY;
if(rotY > 180){
rotY = rotY- 360;
}
if(rotY < -30f) rotY = -30f;
else if(rotY > 30f) rotY = 30f;
//Debug.Log("Rotation de la tête: "+rotY);
var headRotation = new Quaternion();
headRotation = Quaternion.Euler(puppetMasterHeadBone.transform.eulerAngles.x, transform.parent.transform.eulerAngles.y + rotY + -90f, puppetMasterHeadBone.transform.eulerAngles.z);
puppetMasterHeadBone.transform.rotation = headRotation;
}
}
\ No newline at end of file
fileFormatVersion: 2
guid: 89167292edefc9944b1ca58c10c6f185
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
// Variables
[Header("Movement")]
[SerializeField] private float moveSpeed;
[SerializeField] private float walkSpeed;
[SerializeField] private float runSpeed;
private Vector3 moveDirection;
private float computedForwardFloat;
private bool isStoppingForTurn;
private Vector3 velocity;
private Quaternion rotation;
private Rigidbody rb;
[SerializeField] private bool isGrounded;
[SerializeField] private float groundCheckDistance = 0.05f;
[SerializeField] private LayerMask groundMask;
[SerializeField] private float gravity = -9.81f;
[SerializeField] private float jumpHeight;
[Header("Character")]
[SerializeField] private float animationTransitionSpeed = 10f;
[SerializeField] private float animationSpeed = 1f;
[SerializeField] private float turnSpeed = 5f;
// Contrôles
private PlayerInput playerInput;
private InputAction MoveAction;
private InputAction RunAction;
private InputAction JumpAction;
private Vector2 MovementAxis;
private bool runningBtn;
private float playerControllForce;
// Références
private CharacterController controller;
private Animator animator;
private GameObject camera;
// Debug
//[SerializeField] private GameObject debugArrow;
//Awake is called when the script instance is being loaded.
void Awake()
{
playerInput = GetComponentInParent<PlayerInput>();
MoveAction = playerInput.currentActionMap.FindAction("Move");
MoveAction.performed += ctx => MovementAxis = ctx.ReadValue<Vector2>();
MoveAction.canceled += ctx => MovementAxis = Vector2.zero;
RunAction = playerInput.currentActionMap.FindAction("Run");
RunAction.started += ctx => runningBtn = true;
RunAction.canceled += ctx => runningBtn = false;
JumpAction = playerInput.currentActionMap.FindAction("Jump");
JumpAction.started += JumpAction_started;
}
// Start is called before the first frame update
void Start()
{
for (int i = 0; i < Gamepad.all.Count; i++)
{
Debug.Log(Gamepad.all[i].name);
}
//controller = GetComponent<CharacterController>();
rb = GetComponent<Rigidbody>();
animator = GetComponentInChildren<Animator>();
camera = GameObject.Find("Player Camera");
}
// Update is called once per frame
void Update()
{
//Debug.Log("MovementAxis - MovementAxis: "+MovementAxis);
//Debug.Log("momvementRotation - Rotation (controller): "+Mathf.Atan2(MovementAxis.x, MovementAxis.y)* Mathf.Rad2Deg);
Move();
playerControllForce = Mathf.Clamp(Mathf.Abs(MovementAxis.y)+Mathf.Abs(MovementAxis.x), 0, 1);
//rotation = Quaternion.Euler(0, camera.transform.eulerAngles.y, 0);
}
void LateUpdate(){
if(isGrounded){
animator.SetTrigger("grounded");
animator.ResetTrigger("falling");
}else{
animator.SetTrigger("falling");
animator.ResetTrigger("grounded");
}
}
// Appelé à chaque mouvement de l'animator
public void OnAnimatorMove()
{
if (animator){
transform.rotation = animator.rootRotation;
transform.position += animator.deltaPosition;
}
}
void OnDrawGizmosSelected()
{
// Dessine une boule rouge pour visualier goundCheckDistance
Gizmos.color = Color.red;
Gizmos.DrawSphere(transform.position, groundCheckDistance);
}
private void Move()
{
// Récupère les vecteurs de la caméra
var forward = camera.transform.forward;
var right = camera.transform.right;
// On les normalises (0-1)
forward.y = 0f;
right.y = 0f;
forward.Normalize();
right.Normalize();
// On créé la direction
moveDirection = forward * MovementAxis.y + right * MovementAxis.x;
// Rotate player character
if(playerControllForce != 0){/*
var targetTransform = new Quaternion();
targetTransform = Quaternion.Euler(transform.eulerAngles.x, camera.transform.eulerAngles.y + 90 * MovementAxis.x, transform.eulerAngles.z);
transform.rotation = Quaternion.Slerp(transform.rotation, targetTransform, Time.deltaTime * turnSpeed);*/
}
// Check si on est sur le sol ou non (renvoie true/false)
isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);
if(isGrounded && velocity.y < 0){
velocity.y = 0f;
}
if(isGrounded){
Turn();
if(moveDirection != Vector3.zero){
if(runningBtn){
// Run
Run();
}else{
// Walk
Walk();
}
} else {
// Idle
Idle();
}
}
// On applique la direction à suivre sur la flèche de test
//debugArrow.transform.rotation = Quaternion.Euler(moveDirection);
//-Debug.Log("directionCible - Direction cible: "+Quaternion.Euler(moveDirection)); // DebugLog sur l'UI
//controller.Move(moveDirection * Time.deltaTime * moveSpeed);
velocity.y += gravity * Time.deltaTime; // Calcul de la gravité
//controller.Move(velocity * Time.deltaTime); // Application de la gravité
//transform.rotation = rotation; // Rotation
////-Debug.Log("Touche le sol? "+isGrounded);
////-Debug.Log("Vélocité; "+velocity);
//-Debug.Log("velocity - Vélocité: "+velocity); // DebugLog sur l'UI
////-Debug.Log("Forward: " + animator.GetFloat("Forward"));
//-Debug.Log("animatorForwardFloat - Float Forward Animator: "+animator.GetFloat("Forward")); // DebugLog sur l'UI
////-Debug.Log("Turn: " + animator.GetFloat("Turn"));
//-Debug.Log("animatorTurnFloat - Float Turn Animator: "+animator.GetFloat("Turn")); // DebugLog sur l'UI
//-Debug.Log("playerRotation - Rotation (joueur): "+transform.rotation.eulerAngles.y);
//-Debug.Log("player180Rotation - Rotation 180 (joueur): "+((transform.rotation.eulerAngles.y > 180) ? transform.rotation.eulerAngles.y - 360 : transform.rotation.eulerAngles.y));
}
private void Idle(){
animator.speed = animationSpeed;
animator.SetFloat("Forward", Mathf.Lerp(animator.GetFloat("Forward"), 0, animationTransitionSpeed * Time.deltaTime));
}
private void Turn(){
float turnByCameraAngle = 0;
// Permet de faire basculer dans le négatif la rotation du joueur -> comme la direction du Joystick
float rotationDuJoueur = (transform.rotation.eulerAngles.y > 180) ? transform.rotation.eulerAngles.y - 360 : transform.rotation.eulerAngles.y;
float rotationCamera = (camera.transform.rotation.eulerAngles.y > 180) ? camera.transform.rotation.eulerAngles.y - 360 : camera.transform.rotation.eulerAngles.y;
float rotationControllerJoueur = Mathf.Atan2(MovementAxis.x, MovementAxis.y)* Mathf.Rad2Deg;
int signeDiffRotJoueurRotCam = (int)Mathf.Sign(rotationDuJoueur - rotationCamera);
// Debug
Debug.Log("playerRotationMinusCameraRotation - rotationDuJoueur - rotationCamera: "+Mathf.RoundToInt(rotationDuJoueur - rotationCamera));
Debug.Log("rotationControllerJoueurRoundInt - Mathf.RoundToInt(rotationControllerJoueur): "+Mathf.RoundToInt(rotationControllerJoueur));
// Vérification
// Si la rotation arrondie du joueur relative à la caméra est différente de la rotation arrondie du contrôlleur, et que ce dernier n'est pas égal à 0,
if(Mathf.RoundToInt(rotationDuJoueur - rotationCamera) != Mathf.RoundToInt(rotationControllerJoueur) && MovementAxis != Vector2.zero){
// Ici on va regarder si le contrôlleur pointe vers 180°, soit derrière le perso
// Ce qu'il se passe si on ne fait pas ça, c'est que le joueur va tourner dans le sens contraire s'il est vers la gauche, vu que 180 >0
if(rotationControllerJoueur == 180f || rotationControllerJoueur == 0f){
rotationControllerJoueur *= (int)signeDiffRotJoueurRotCam;
}else{
if(signeDiffRotJoueurRotCam != Mathf.Sign(rotationControllerJoueur)){
// Ici on va regarder s'il n'est pas plus court de continuer à tourner dans le négatif, vu que la rotation du contrôlleur, si elle est positive, demandera toujours au perso de tourner vers le positif
float versLeNegatif = Mathf.Abs(signeDiffRotJoueurRotCam * 180 - rotationDuJoueur) + Mathf.Abs(signeDiffRotJoueurRotCam * (-1) * 180 - rotationControllerJoueur);
float versLePositif = Mathf.Abs(rotationDuJoueur) + Mathf.Abs(rotationControllerJoueur);
if(versLeNegatif < versLePositif){
rotationControllerJoueur = signeDiffRotJoueurRotCam*200; // On attribut une valeur inférieur à -180 pour forcer le perso à tourner dans le sens contraire
// Une fois dépassé les -180, la rotation du joueur passera en positif, et le calcul se fera normalement
// La valeur (200) est aribtraire
}
}
}
// On initialise une variable qui nous servira pour le signe de la rotation (positif ou negatif)
int rotationSign = 1;
rotationSign = (int)Mathf.Sign((rotationCamera + rotationControllerJoueur)-rotationDuJoueur);
// Ici, il faudrait faire un lerp
if(Mathf.RoundToInt(rotationDuJoueur - rotationCamera) > Mathf.RoundToInt(rotationControllerJoueur) -5 && Mathf.RoundToInt(rotationDuJoueur - rotationCamera) < Mathf.RoundToInt(rotationControllerJoueur) +5){
turnByCameraAngle = (rotationSign * 0.1f);
}else{
if (runningBtn)
{
turnByCameraAngle = (rotationSign * 1.0f);
}
else
{
turnByCameraAngle = (rotationSign * 0.5f);
}
}
}
// Pour retourner le perso si on fait un 180°
if (isStoppingForTurn)
{
if (moveDirection != Vector3.zero)
{
if(Mathf.Abs((Mathf.RoundToInt(rotationDuJoueur - rotationCamera) - Mathf.RoundToInt(rotationControllerJoueur))) < 5){
isStoppingForTurn = false;
}
}
else
{
isStoppingForTurn = false;
computedForwardFloat = 1;
}
}
else
{
if((Mathf.Abs(Mathf.RoundToInt(rotationDuJoueur - rotationControllerJoueur)) > 170 &&
Mathf.Abs(Mathf.RoundToInt(rotationDuJoueur - rotationControllerJoueur)) < 190)){
isStoppingForTurn = true;
computedForwardFloat = 0;
}
else
{
if(computedForwardFloat != 1.0f){
computedForwardFloat = 1.0f;
}
}
}
// Application
//Mathf.Atan2(MovementAxis.x, MovementAxis.y)* Mathf.Rad2Deg
animator.speed = Mathf.Clamp(Mathf.Abs(MovementAxis.y)+Mathf.Abs(MovementAxis.x), 0, 1) * animationSpeed;
//animator.SetFloat("Turn", Mathf.Lerp(animator.GetFloat("Turn"), Mathf.Clamp(MovementAxis.x + (float)turnByCameraAngle, -1, 1), animationTransitionSpeed * Time.deltaTime));
animator.SetFloat("Turn", Mathf.Lerp(animator.GetFloat("Turn"), turnByCameraAngle, animationTransitionSpeed * Time.deltaTime));
}
private void Walk(){
// Ici on limite la valeur à 1. Le calcul est basé sur la valeur du controleur en x et y. Cela permet de ne pas dépendre d'un seul axe
animator.speed = Mathf.Clamp(Mathf.Abs(MovementAxis.y)+Mathf.Abs(MovementAxis.x), 0, 1) * animationSpeed;
animator.SetFloat("Forward", Mathf.Lerp(animator.GetFloat("Forward"), 0.5f * computedForwardFloat, animationTransitionSpeed * Time.deltaTime));
moveSpeed = walkSpeed;
}
private void Run(){
animator.speed = animationSpeed;
animator.SetFloat("Forward", Mathf.Lerp(animator.GetFloat("Forward"), 1 * computedForwardFloat, animationTransitionSpeed * Time.deltaTime));
moveSpeed = runSpeed;
}
private void Jump(){
velocity.y = Mathf.Sqrt(jumpHeight * -3.0f * gravity);
}
// Fonction des Contrôles
public void JumpAction_started(InputAction.CallbackContext context){
if (isGrounded){
Jump();
}
}
}
fileFormatVersion: 2
guid: b2db16020daec97499c8c4ad01a92d3a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment